3

我需要在运行时构建一个 where 子句,但我需要对 where 子句进行 OR。这可能吗..让我解释一下..

这里我的代码......,基本上“过滤器”是一个枚举按位,儿子因此过滤器可能等于以下1个以上......因此我需要建立where子句......

如果我单独执行 wheres,而不是想象我先执行 Untested,它返回 0 条记录,这意味着我无法在 Tested 上执行 where,因为它现在有 0 条记录。

我会在下面放一些伪代码:-)

        string myWhere = "";

        if ((filter & Filters.Tested) == Filters.Tested)
        {
             if (myWhere != "" ) myWhere =myWhere + "||";
             myWhere = myWhere " Status == "Tested";

        }

        if ((filter & Filters.Untested) == Filters.Untested)
        {
             if (myWhere != "" ) myWhere =myWhere + "||";
             myWhere = myWhere " Status == "Untested";
        }

        if ((filter & Filters.Failed) == Filters.Failed)
        {
             if (myWhere != "" ) myWhere =myWhere + "||";
             myWhere = myWhere " Status == "Failed";
        }

        // dataApplications = a List of items that include Tested,Failed and Untested.

        // dataApplciation.Where ( myWhere) ---  Confused here!  

这可能吗..

我不想包含很多“IF”,因为有很多组合,即没有过滤器,过滤器=仅测试,过滤器=未经测试和测试......等等

任何想法都非常感谢

谢谢

4

3 回答 3

4

如果你有这个:

IEnumerable<MyType> res = from p in myquery select p;

你可以定义一个

var conditions = new List<Func<MyType, bool>>();

conditions.Add(p => p.PropertyOne == 1);
conditions.Add(p => p.PropertyTwo == 2);

res = res.Where(p => conditions.Any(q => q(p)));

现在制作匿名对象函数列表的技巧(您可以轻松地将其更改为“提取”匿名对象的类型)

static List<Func<T, bool>> MakeList<T>(IEnumerable<T> elements)
{
    return new List<Func<T, bool>>();
}

您可以通过传递 LINQ 查询的结果来调用它。所以

var res = from p in elements select new { Id = p.Id, Val = p.Value };
var conditions = MakeList(res);
于 2011-02-20T11:13:44.443 回答
3
var statusTexts = new List<string>(); // Add desired status texts
dataApplication.Where(item =>
        statusTexts.Any(status => item.Status == status))
于 2011-02-20T11:19:34.193 回答
0

将 HashSet<> 用于状态,然后.Contains将 O(1) 而不是通常的 O(n) 用于 List<>:

var statuses = new HashSet<string>() {"a", "b", "c"};
var list = new[] {
    new {   Id = 1, status = "a"},
    new {   Id = 2, status = "b"},
    new {   Id = 3, status = "z"}
};

var filtered = list.Where(l => statuses.Contains(s => l.status == s));
于 2015-06-25T07:57:57.820 回答