我需要在linq中编写一个条件查询:
如果field.val1 == 0:
var q = from field in cw.fields
select field
如果field.val1!= 0且field.val2 == 0:
var q = from field in cw.fields
where field.val1 == 1
select field
如果field.val1!= 0且field.val2!= 0:
var q = from field in cw.fields
where field.val1 == 1 and field.val2 == 1
select field
我该怎么做?
答案 0 :(得分:2)
由于您的条件取决于您的查询值,因此您只需使用where
扩展||
子句以及其他案例:
var q = from field in cw.fields
where
(field.val1 == 0) ||
(field.val1 != 0 and field.val2 == 0 && field.val1 == 1) ||
(field.val1 != 0 and field.val2 != 0 && field.val1 == 1 and field.val2 == 1)
select field
答案 1 :(得分:2)
@ MarcinJuraszek的答案会起作用,但让我给出一个不同的观点。
首先,抛弃sql样式语法。它阻碍了实际发生的事情,通常只是一种感觉良好的抽象,而不是一种会产生更多交际代码的抽象。让我们用lambda语法重写一些东西
IEnumerable<string> getFields(SomeField field, YourDatabase cw) {
if(field.val1 == 0:)
return cw.fields.ToList();
if(field.val1 != 0 and field.val2 == 0)
return cw.fields.Where(f => f.val1 ==1).ToList();
if(field.val1 != 0 and field.val2 != 0)
return cw.fields.Where(f => f.val1 == 1 and f.val2 == 1).ToList();
}
请注意,事物不同的唯一方法是lambda,lambda是一个对象,在本例中是一个Expression对象!所以你可以在这里使用一个非常标准的抽象工厂模式
return cw.fields.Where(matchingCondition(field)).ToList();
//elsewhere...
Expression<Func<SomeField, bool>> matchingCondition(SomeField field) {
if(field.val1 == 0:) return f => true;
if(field.val1 != 0 and field.val2 == 0) return f => f.val1 == 1
if(field.val1 != 0 and field.val2 != 0) return f => f.val1 == 1 and f.val2 == 1;
throw new InvalidOperationException("No match to condition");
}