Combine and / or with PredicateBuilder?

I have a list of Ids , and I want to do only AND for the first, and OR for the following. I used to save the counter variable, and when counter is 1, I do AND , but after that I do OR , but I was curious if there was an easier way: / p>

 foreach(string id in Ids) { predicate.And(x=> id.Contains(x.id)); //I want to do an And only on the first id. } 

This is what I have done in the past, but there is a more concise way:

 int counter = 1; foreach (var Id in Ids) { string i = Id; if (counter == 1) { predicate = predicate.And(x => i.Contains(x.id)); counter++; } else { predicate = predicate.Or(x=>i.Contains(x.id)); counter++; } } 
0
source share
1 answer

This works with a local copy of PredicateBuilder (without working with entityFramework or LinkToSql):

 var firstID = ids.First(); predicate.And(x => firstID.Contains(x.id)); foreach (string id in ids.Skip(1)) { var localID = id; //access to a modified closure otherwise predicate.Or(x => localID.Contains(x.id)); } 
+1
source

Source: https://habr.com/ru/post/984646/


All Articles