I have the following foreach expression within which I am building a predicate and then filtering the collection by executing .Where().
But what stumps me is, result.Count() gives me 0 even before I execute .Where() in the next iteration.
var result = SourceCollection;
foreach (var fieldName in FilterKeys)
{
if (!conditions.ContainsKey(fieldName)) continue;
if (!conditions[fieldName].IsNotNullOrEmpty()) continue;
var param = conditions[fieldName];
Func<BaseEntity, bool> predicate = (d) => fieldName != null && d.GetFieldValue(fieldName).ContainsIgnoreCase(param);
result = result.Where(predicate);
}
Does, anybody know of any LINQ behavior that I might have overlooked that is causing this?
I think, you want this:
Notice the use of
fin the predicate. You don’t want to capture the foreach variable. In your original code, when the second iteration starts, param is still the captured value from the first iteration, but fieldName has changed.