i want to combine some Linq Expression, so i help from below articles:
http://www.c-sharpcorner.com/uploadfile/04fe4a/predicate-combinators-in-linq/ and http://thanhhh.blogspot.com/2011/10/linq-to-entities-predicatebuilder-and.html
and i have a generic list like this:
List<long> lstPA = new List<long>() { 2, 3 }; // the numbers can be added or removed
if i use under code for combine my linq expression, i get correct results(records) from db (i use Entity Framework 4.0):
var exp1 = Predicate.FalseExpression<posts>();
exp1 = exp1.Or(x => x.post_author == 2);
exp1 = exp1.Or(x => x.post_author == 3);
but when i combine linq expression in a foreach loop Like this:
var exp1 = Predicate.FalseExpression<posts>();
foreach (long id in lstPA)
{
exp1 = exp1.Or(x => x.post_author == id);
}
i can't get correct result(records) from db.
what is diffrence between 2 code blocks and how can solve this problem (i must use foreach loop)?
I believe your issue is to do with closure. The variable id is assigned to the expression and it updates to a newer value each time you loop. In order to use it you want to make an individually scoped variable.
However you could just use the contains clause instead in this instance.