我们可以动态追加linq查询的条件吗?
例如:
class Result
{
string v1;
string v2;
string v3;
}
List<Result> result = (from r in results select r);
//i want to do something like the following....
if(conditionA)
{
result = result appened (or v1 = xxx)
}
else if(conditionB)
{
result = result appened (or v2 = xxx)
}
else if(conditionC)
{
result = result appened (or v3 == xxx)
}
任何人都知道如何处理Linq ????
中的情况的Th
答案 0 :(得分:3)
如果要动态构建它,可以使用 PredicateBuilder
答案 1 :(得分:2)
只需将Where
查询运算符附加到您的查询中:
if(conditionA)
{
result = result.Where(r => r.v1 == xxx);
}
else if(conditionB)
{
result = result.Where(r => r.v2 == xxx);
}
else if(conditionC)
{
result = result.Where(r => r.v3 == xxx);
}
请注意,您的results
变量应声明为IEnumerable<Result>
,而不是List<Result>
答案 2 :(得分:2)
对于and
子句的关系,您可以轻松添加.Where()
过滤器方法,如下:
where conditionOriginal(r) and conditionDynamic(r)
作为
var results = (from r in originalResults
where originalConditions(r)
select r);
...
if (conditionA)
results = results.Where(r => conditionDynamic(r));
要附加'或'类型关系,您必须与原始结果集合并,如下所示:
where conditionOriginal(r) or conditionDynamic(r)
变为
var results = (from r in originalResults
where conditionOriginal(r)
select r);
...
if (conditionB)
results = results.Union((from r in originalResults
where conditionDynamic(r)
select r));
或
if (conditionB)
results = results.Union(originalResults.Where(conditionDynamic(r)));
答案 3 :(得分:1)
你可以这样做:
if (conditionA)
{
result = result.Where(p => p.v1 == xxx); // Just guessing at the intent here.
}
// Repeat as necessary...
或者这个:
if (conditionA)
{
result = from r in result where p.v1 == xxx select r;
}
答案 4 :(得分:0)
由于Linq会延迟执行,你可以只追加查询的位置,并在最后执行tolist来执行:
var query = from r in results;
//i want to do something like the following....
if(conditionA)
{
query = result.Where(x => x.v1 = xxx);
}
else if(conditionB)
{
query = result.Where(x => x.v2 = xxx);
}
else if(conditionC)
{
query = result.Where(x => x.v1 = xxx);
}
List<Result> result = query.ToList();
答案 5 :(得分:0)
其他答案是最简单的解决方案。如果你想要一次执行,你也可以使用表达式树:
http://blogs.msdn.com/abhinaba/archive/2006/03/01/541179.aspx http://www.devsource.com/c/a/Languages/Understanding-LINQ-Expression-Trees/1/
答案 6 :(得分:0)
好吧,你总是可以在where子句中调用一个函数,并在那里建立你的条件:
...
public bool MeetsConditions(Result r, bool a, bool b)
{
bool result = false;
if(a) result = result || r.v1==xxx
if(b) result = result && r.v2==xxx
return result;
}
...
var q = select from r in results where MeetsConditions(r, conditionA, conditionB)