LINQ:构建动态的过滤器与运算顺序过滤器、顺序、动态、LINQ

2023-09-05 04:34:01 作者:花开依旧

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

 词典<字符串的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到对象通过支持它总结

.NET 学习诀窍 LINQPad

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.