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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With