user584018
user584018

Reputation: 11304

how to put conditional WHERE clause within LINQ query

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'

Upvotes: 5

Views: 1453

Answers (2)

TheGeneral
TheGeneral

Reputation: 81483

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;

Upvotes: 2

Ian Kemp
Ian Kemp

Reputation: 29839

Just move the condition into the lambda:

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

Upvotes: 4

Related Questions