Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query if condition external parameter

I'm trying to use LINQ to get a list of values.

I have code like this:

var _context = _scope.ServiceProvider.GetRequiredService<VMContext>();

if (boolparameter)
{
    var listCE = _context.Ce
                         .Where(x => x.VuId == element.VuId)
                         .Where(x => x.Score == 8)
                         .AsNoTracking()
                         .ToList();
}
else
{
    var listCE = _context.Ce
                         .Where(x => x.VuId == element.VuId)
                         .AsNoTracking()
                         .ToList();
}

Depends on boolparameter, I do a query or another one. Is there a way to use a single query with a conditions inside? Something like:

var listCE = _context.Ce
                     .Where(x => x.VuId == element.VuId)
                     .Where(x => boolparameter ? x.Score == 8 : true)
                     .AsNoTracking()
                     .ToList();

C# Asp.NetCore SqlServer 2019 Thanks a lot!

like image 882
Rob None Avatar asked Mar 02 '23 21:03

Rob None


1 Answers

You could try the following code if it works:

var listCE = _context.Ce
  .Where(x => x.VuId == element.VuId)
  .Where(x => !boolparameter || x.Score == 8)
  .AsNoTracking()
  .ToList();

Which means if boolparameter is false, x.Score doesn't matter, since !false would equal to true and it satisfies OR condition. Likewise if boolparameter is true, then x.score will also be checked if it is equal to 8.

Or maybe with one Where condition:

var listCE = _context.Ce
  .Where(x => x.VuId == element.VuId && (!boolparameter || x.Score == 8))
  .AsNoTracking()
  .ToList();
like image 148
Jure Avatar answered Mar 07 '23 01:03

Jure