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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With