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'
Just move the condition into the lambda:
var g = mast.Where(w => (condition
? (w.Prop1.ToLower() != "default" || w.Prop2.ToLower() != "data")
: true)
).ToList();
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;
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