Reputation: 41
In my query I am getting records based on RoleId
and LocationId
, some times the user may not pass location in that case I want to remove that filter and get information from all locations.
Currently I am doing this way
if(loc > 0)
{
var myResult = (from x in CSDB.Allocations
join s in CSDB.Managers
on x.ManagerId equals s.Id
Where x.RoleId == 2 && s.LocationId == loc
select new
{
x.name,
x.Date
}).ToList();
}
else
{
var myResult = (from x in CSDB.Allocations
join s in CSDB.Managers
on x.ManagerId equals s.Id
Where x.RoleId == 2
select new
{
x.name,
x.Date
}).ToList();
}
I am seeing if I can check if loc
is null or not inside the query instead of using if else.
Upvotes: 1
Views: 575
Reputation: 1026
Also, you can do smth like this.
Where x.RoleId == 2 && (loc?.Equals(s.LocationId) ?? true)
If loc
just int
I would prefer to use a little bit changed @Salah Akbari answer:
Where x.RoleId == 2 && (loc == 0 || s.LocationId == loc)
Upvotes: 1
Reputation: 1904
Simply extract your managers and filter them if needed. That way you can as well easily apply more filters and code readability isn't hurt.
var managers = CSDB.Managers.AsQueryable();
if(loc > 0)
managers = managers.Where(man => man.LocationId == loc);
var myResult = from allocation in CSDB.Allocations
join manager in managers on allocation.ManagerId equals manager.Id
where allocation.RoleId == 2
select new
{
allocation.name,
allocation.Date
};
Upvotes: 0
Reputation: 39956
You can do something like this:
Where x.RoleId == 2 && (loc == null || s.LocationId == loc)
Upvotes: 2