The problem with using a predicate builder in a foreach loop

I'm having trouble building predicates in a foreach loop. The variable containing the value that the enumerator currently includes is what I need to add to the predicate.

So,

IQueryable query = getIQueryableSomehow();
Predicate = PredicateBuilder.False<SomeType>();
foreach (SomeOtherType t in inputEnumerable)
{
    Predicate = Predicate.Or( x => x.ListInSomeType.Contains(t) )
}
var results = query.Where(Predicate);

fails. The ORed expressions together in Predicate basically all use the same t from inputEnumerable, when, of course, I want each ORed expression in Predicate to use a different t from inputEnumerable.

I looked at the predicate in the debugger after the loop, and it looks like IL. In any case, every lambda there looks exactly the same.

Can someone tell me what I can do wrong here?

Thank,

Isaac

+5
2

, . SomeOtherType t , :

foreach (SomeOtherType t in inputEnumerable) 
{ 
    SomeOtherType localT = t;
    Predicate = Predicate.Or( x => x.ListInSomeType.Contains(localT) ) 
}

. #

+4

. SomeOtherType .

foreach (SomeOtherType t in inputEnumerable)
{
    var someOtherType = t;
    Predicate = Predicate.Or( x => x.ListInSomeType.Contains(someOtherType) )
}
+1

All Articles