LINQ:构建动态的过滤器与运算顺序 [英] LINQ: Build dynamic filter with sequence of ANDs

查看:111
本文介绍了LINQ:构建动态的过滤器与运算顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我挣扎动态创建一个这样的查询:

 词典<字符串的Guid> PARMS =新字典<字符串的Guid>();

的foreach(在PARMS VAR KVP)
{
    VAR EXP = ReportDefinitions.Where(X =>
        x.Discriminants.Any(Y => y.Key == kvp.Key和放大器;&安培; y.Value == kvp.Value)
//&功放;&安培;更多的条件,在这里添加在每个周期
        );
}
 

在哪里ReportDefinitions.Discriminants是的IDictionary<字符串的Guid> ; 我知道如何建立简单的防爆pression,但我无法弄清楚如何建立这一个任意似乎非常复杂。 在任何呼叫很难undestand

任何人都知道该如何处理呢?

解决方案

  VAR的查询= parms.Aggregate(ReportDefinitions.AsQueryable()
  (一,KVP)=> a.Where(X => x.Discriminants.Any(
     Y => y.Key == kvp.Key和放大器;&安培; y.Value == kvp.Value)));
 

我们正着手与ReportDefinitions的未经过滤的查询,并折叠所有查询参数。最终的结果是嵌套滤波器的序列,相当于与运算的序列。

关键的观点是,这个过程很好地映射到的减少的从函数式语言知。 LINQ到对象通过支持它总结

I'm struggling to dynamically create a query like that:

Dictionary<string, Guid> parms = new Dictionary<string, Guid>();

foreach (var kvp in parms)
{
    var exp = ReportDefinitions.Where(x=> 
        x.Discriminants.Any(y=> y.Key == kvp.Key && y.Value == kvp.Value)
// && more conditions to add here at each cycle
        );  
}

Where ReportDefinitions.Discriminants is an IDictionary<string, Guid>; I know how to build simple Expression but I can't figure out how to build this one the "Any" seems really complicated. The Any call it's hard to undestand

Anyone knows how to deal with this ?

解决方案

var query = parms.Aggregate(ReportDefinitions.AsQueryable(),
  (a, kvp) => a.Where(x => x.Discriminants.Any(
     y => y.Key == kvp.Key && y.Value == kvp.Value)));

We are starting with an unfiltered query of ReportDefinitions and are folding in all query params. The end result is a sequence of nested filters which is equivalent to a sequence of ANDs.

The key insight is that this process maps nicely to a reduce known from functional languages. LINQ to objects supports it via Aggregate.

这篇关于LINQ:构建动态的过滤器与运算顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆