简体   繁体   中英

Check if parameter value is null or not inside query

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.

你可以这样做:

Where x.RoleId == 2 && (loc == null || s.LocationId == loc)

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)

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
               };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM