Recently in a webapi encounter a need to merge multiple predicate conditions, the following is the case of the problem. To facilitate communication I have simplified the case, please look at the following code:
usingSystem.Collections.Generic;usingSystem.Linq;namespacecombinelinqpredicates{ Public classCustomer { Public intId {Get;Set; } Public stringName {Get;Set; } Public stringURL {Get;Set; } } classProgram {Static voidMain (string[] args) { varCustomers =GetCustomers (); varFiltercustomers = Customers. Where (x = X.id = =2); } Private StaticIenumerable<customer>GetCustomers () {return NewList<customer>() { NewCustomer () {id=1, name="Alibaba", url="http://www.taobao.com"}, NewCustomer () {id=2, name="Jd", url="http://www.jd.com"}, NewCustomer () {id=3, name="Tencent", url="http://www.qq.com"} }; } }}
The code is very simple, and a customer object has three attributes, ID, name, and URL. And a method getcustomers the customer list in the past.
In the main method, I pass
var filtercustomers = customers. Where (x = X.id = = 2
Gets all the customer objects with id = 2.
If the ID in the Where condition needs to be fetched from the UI now, and I need to add another condition, such as how does the URL contain the JD string?
The code may become:
int? Inputcustomerid =NULL; stringInputurl =NULL; varCustomers =GetCustomers (); //we omit the process of getting values from the UI and populating them with Inputcustomerid,inputurl. varFiltercustomers =customers; if(inputcustomerid.hasvalue) Filtercustomers = filtercustomers.where (x = X.id = =inputcustomerid.value); if(!string. IsNullOrEmpty (inputurl)) Filtercustomers = filtercustomers.where (x = X.url.contains (Inputurl));
In the above code there are two filters, in order to avoid this problem, improve performance, we need to merge these two where conditions.
First we look at the definition of where condition:
public static ienumerable<tsource> where<tsource> (this ienumerable<tsource> source, func< TSource, bool> predicate);
His parameter type is Func<tsource, bool> type, so I can define a type as follows, and then merge it with the following code:
bool> idfilter = x = Inputcustomerid.hasvalue && x.id = = Inputcustomerid.value; Funcbool> urlfilter = x = =! string. IsNullOrEmpty (inputurl) && x.url.contains (inputurl); Funcbooltrue && idfilter (x) && urlfilter (x); = Customers. Where (filter);
After this process, the problem of two filters is resolved.
How to combine multiple predicate conditions in LINQ