Home > Mobile >  Ternary If in LINQ Query C#
Ternary If in LINQ Query C#

Time:11-24

Hi guys i have this code:

var sites = context.SITES.OrderBy(s => s.NAME).ToList();
 if (userId != 0)
     sites = context.SITES.OrderBy(s => s.NAME).Where(s => s.Users.Any(x => x.ID == userId)).ToList();

Is it possible to make the if inside the query? I need to do this code in one line

var sites = context.SITES.OrderBy(s => s.NAME) 
if(userId != 0) {
    .Where(s => s.Users.Any(x => x.ID == userId)) 
}
.ToList();

I want something like this

CodePudding user response:

You can make use of the 'deferred execution' nature of IQueryable/Entity Framework here. So start with your initial query:

IQueryable<Site> query = context.SITES;

Now add a filter if needed:

if(userId != 0) {
    query = query.Where(s => s.Users.Any(x => x.ID == userId)) ;
}

Finally, add in the ordering and enumerate the result with the ToList:

var list = query.OrderBy(s => s.NAME).ToList();

CodePudding user response:

You can make a slight modification to get it to work:

IQueryable<Site> sites = context.SITES.OrderBy(s => s.NAME) 
if(userId != 0) {
    sites = sites.Where(s => s.Users.Any(x => x.ID == userId)) 
}

Or you could inline the if this way:

var sites = sites.Where(s => (userId == 0) || (s.Users.Any(x => x.ID == userId))) 
                 .OrderBy(s => s.NAME)
                 .ToList()
  • Related