That's because LINQ is lazy and filtered
is not a collection - it's an in-memory query, which just stores information how to evaluate result, not the result itself. Because of that, every time you use filtered
it's being evaluated again, iterating over GroupedList
and checking where
condition again.
It means, where
condition will be evaluated orders.Count() * GroupedList.Count()
times.
Add ToList()
call to filtered
to evaluate it eagerly.
var filtered =
(from g in GroupedList
where IncrementProgress(max, ref count)
select g.Id).ToList();
But, because you're only using Contains
on filtered
later, you should use HashSet<int>
to store results. It will make Contains
call O(1) instead of O(n), which should increase performance a lot.
var filtered =
new HashSet<int>(from g in GroupedList
where IncrementProgress(max, ref count)
select g.Id);