LINQ: Build dynamic filter with sequence of ANDs

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-04 04:35:12

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/11365267/linq-build-dynamic-filter-with-sequence-of-ands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!