我正在尝试在condition
为真的情况下进行操作,我想执行WHERE
,否则为否。
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();
上面的代码给了我错误,
由于'lambda表达式'和'bool'之间没有隐式转换,因此无法确定条件表达式的类型
答案 0 :(得分:4)
只需将条件移到lambda中即可:
var g = mast.Where(w => (condition
? (w.Prop1.ToLower() != "default" || w.Prop2.ToLower() != "data")
: true)
).ToList();
答案 1 :(得分:2)
您只需使用1个lambda变量x=>
或者您可以只检查条件为真还是其他条件为真
var result = mast.Where(x=> !condition || (x.Prop1.ToLower() != "default" || x.Prop2.ToLower() != "data");
或者您可以只使用if
语句
IEnumerable<Master> result;
if (condition)
result = mast.Where(x => x.Prop1.ToLower() != "default" || x.Prop2.ToLower() != "data");
else
result = mast;