Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading