问题
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