我们可以动态地在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中的状况吗????

最佳答案

对于子句的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)));

关于c# - 如何在有条件的地方使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2330722/

10-12 00:04
查看更多