Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put conditional WHERE clause within LINQ query

Tags:

c#

lambda

linq

I'm trying to do below where condition is true, I want to execute WHERE else no.

var condition = true;

var mast = new List<Master>
{
    new Master{Id = 2, Prop1 = "Default", Prop2 = "Data", Prop3 = 11},
    new Master{Id = 3, Prop1 = "Some", Prop2 = "TestData", Prop3 = 11},
    new Master{Id = 4, Prop1 = "Some", Prop2 = "MoreData", Prop3 = 11},
};

var g = mast.Where(w=> condition ? (x => x.Prop1.ToLower() != "default" || x.Prop2.ToLower() != "data") : true = true).ToList();

Above code giving me error,

Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'bool'

like image 346
user584018 Avatar asked Mar 05 '19 04:03

user584018


2 Answers

Just move the condition into the lambda:

var g = mast.Where(w => (condition
    ? (w.Prop1.ToLower() != "default" || w.Prop2.ToLower() != "data")
    : true)
).ToList();
like image 126
Ian Kemp Avatar answered Oct 19 '22 13:10

Ian Kemp


You could just fix your original statement with correct lambda notation by using only 1 lambda variable x=>

Or you could just check if the condition is true or your other conditions are true

var result = mast.Where(x=> !condition || (x.Prop1.ToLower() != "default" || x.Prop2.ToLower() != "data");

Or you could just use an if statement

IEnumerable<Master> result;
if (condition)
   result = mast.Where(x => x.Prop1.ToLower() != "default" || x.Prop2.ToLower() != "data");
else
   result = mast;
like image 41
TheGeneral Avatar answered Oct 19 '22 13:10

TheGeneral