【问题标题】:Filter Products in a Dynamic Way using LINQ使用 LINQ 以动态方式过滤产品
【发布时间】:2012-08-09 19:08:21
【问题描述】:

经过数小时的尝试和搜索,我想现在是时候与您分享我的问题了。

问题定义: 我有一个 KeyValuePairs 字典(名为 filterPool),其中包括一个整数(PropertyID)和一个字符串(McValue )。我要做的是根据这些 KeyValuePairs 过滤产品并将它们作为 DataTable/List 返回。 您可以将其视为将动态“Where ... And ..”子句构建为 SQL。

这是我正在使用的代码:

            foreach (KeyValuePair<int, string> filter in filterPool)
            {
                products = products.Where(i => i.PROPERTYID == filter.Key && i.MCVALUE.Equals(filter.Value));
            }
            return products.ToDataTable();                  

问题是上面的 foreach 循环似乎只工作一次,对于字典中可用的最新 KeyValuePair。

据我在 Stackoverflow 上找到的,最接近我的问题的解决方案是:this one, also using a Dictionary of values for filtering

一定有办法使用Dictionary和LINQ实现过滤的目的;或者有一件我想念/忽略的大事。

希望给出的问题对所有人来说都足够清楚, 谢谢 ^^

【问题讨论】:

    标签: asp.net linq dictionary code-behind dynamicquery


    【解决方案1】:

    这是一个关闭问题。您可以通过临时解决它:

            foreach (KeyValuePair<int, string> filterTmp in filterPool)
            {
                var filter = filterTmp; // Make a temporary
                products = products.Where(i => i.PROPERTYID == filter.Key && i.MCVALUE.Equals(filter.Value));
            }
            return products.ToDataTable();   
    

    有关正在发生的事情的详细信息,请参阅 Eric Lippert 的帖子 Closing over the loop variable considered harmful

    另请注意,C# 5 的此行为已更改。在 C# 5/VS2012 中,此代码将按预期工作。

    【讨论】:

    • 感谢 Reed,由于远程 SQL Server 的连接问题,我现在无法尝试您的解决方案建议。我会尽快尝试的!再次感谢您的快速回复。
    【解决方案2】:

    您在 foreach 的每次迭代中都覆盖了您的产品集合。我不确定你的集合中的数据类型是什么,但你会想在你的 foreach 中做这样的事情:

    products.AddRange(products.Where(i => i.PROPERTYID == filter.Key && i.MCVALUE.Equals(filter.Value)));
    

    我不确定这是否有意义,但您似乎正在尝试创建一个包含与您的 filterPool 匹配的产品的集合。

    【讨论】:

      【解决方案3】:

      我认为用聚合更好地解决:

      return filter
          .Aggregate(products, (acc, filter) => acc.Where(i => i.PROPERTYID == filter.Key && i.MCVALUE.Equals(filter.Value)));
          .ToDataTable();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-15
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-27
        相关资源
        最近更新 更多