Ternary If in LINQ Query C#

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

>Solution :

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

var 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()

Leave a Reply