c# - Implicitly typed local variables must be initialised -


i want dynamically put condition :-

var data; if(employeid != 0) {  data = (from in ctx.tblto1              join b in ctx.tblto2                     on a.company equals b.company                     a.id == b.id &&                     a.employeeid == employeeid                     select new { = a, b = b }).tolist(); }else{      data = (from in ctx.tblto1                  join b in ctx.tblto2                         on a.company equals b.company                         a.id == b.id &&                         a.cat == cats                         select new { = a, b = b }).tolist(); } 

the result of above expression of anonymous type. not able declare & 1st line gives error. implicitly typed local variables must initialised.

what way solve this? can use separate function, functions return type?

well, of course var data; makes no sense.

you define type appropriate fields element type. particularly useful if same type comes more once.

you use ?: here use if…else:

var data = (employeeid != 0)   ? (from in ctx.tblto1      join b in ctx.tblto2       on a.company equals b.company       a.id == b.id &&         a.employeeid == employeeid         select new { = a, b = b }).tolist()   : (from in ctx.tblto1      join b in ctx.tblto2        on a.company equals b.company        a.id == b.id &&          a.cat == cats          select new { = a, b = b }).tolist(); 

but perhaps clearest modify query differs each case:

var query = in ctx.tblto1             join b in ctx.tblto2             on a.company equals b.company             a.id == b.id             select new { = a, b = b };  if (employeeid != 0)   query = query.where(i => i.a.employeeid == employeeid); else    query = query.where(i => i.a.cat == cats); var data = query.tolist(); 

this has advantage of making difference between 2 cases clearer in code. separating out tolist() has advantage of making clearer if change code in such way no longer need it.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -