Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly typed local variables must be initialised

I want to dynamically put a condition like this :-

var data;
if(employeId != 0) {
 data = (from a in ctx.tblTO1
             join b in ctx.tblTO2
                    on a.Company equals b.Company
                    where a.Id == b.Id &&
                    a.employeeId == employeeId
                    select new { a = a, b = b }).ToList();
}else{
     data = (from a in ctx.tblTO1
                 join b in ctx.tblTO2
                        on a.Company equals b.Company
                        where a.Id == b.Id &&
                        a.Cat == cats
                        select new { a = a, b = b }).ToList();
}

The result of the above expression is of Anonymous Type. So i am not able to declare it & the 1st line gives error. Implicitly typed local variables must be initialised.

What is the way to solve this? Can we use a separate function, but then what will be the functions return type?

like image 554
Anup Avatar asked Dec 07 '25 07:12

Anup


1 Answers

Well, of course var data; makes no sense.

You could define a type with the appropriate fields to be the element type. This is particularly useful if the same type comes up more than once.

You could also use ?: where you here use if…else:

var data = (employeeId != 0)
  ? (from a in ctx.tblTO1
     join b in ctx.tblTO2
      on a.Company equals b.Company
      where a.Id == b.Id &&
        a.employeeId == employeeId
        select new { a = a, b = b }).ToList()
  : (from a in ctx.tblTO1
     join b in ctx.tblTO2
       on a.Company equals b.Company
       where a.Id == b.Id &&
         a.Cat == cats
         select new { a = a, b = b }).ToList();

But perhaps the clearest is to modify a query for just what differs with each case:

var query = from a in ctx.tblTO1
            join b in ctx.tblTO2
            on a.Company equals b.Company
            where a.Id == b.Id
            select new { a = 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 the advantage of making the difference between the two cases clearer in the code. Separating out the ToList() also has the advantage of making it clearer if you change your code in such a way as to no longer need it.

like image 101
Jon Hanna Avatar answered Dec 08 '25 21:12

Jon Hanna