Reputation: 3370
I have a list of items, and I want to select 3 items from that list that fulfills a predicate.
I've tried this: (examples)
list.Where(x => x == 2).Take(3)
list.Take(3).Where(x => x == 2)
But of course they don't work.
Is there a mechanism that only selects elements that meets a predicate until the .Take(3)
is fulfilled?
EDIT: The problem with the first example is that it first selects EVERY element that matches, then takes the first 3. I only want it to select until it has taken 3. I suppose it only really matters on huge collections, but still. Or that's how I understand it anyway.
This happens: (edit: I was wrong about this)
[1, 2, 2, 2, 3, 4, 5, 2].Where(x => x == 2)
=> [2, 2, 2, 2].Take(3)
=> [2, 2, 2]
I want something like:
[1, 2, 2, 2, 3, 4, 5, 2].Where(x => x == 2, 3)
=> [2, 2, 2]
, where the 3 is the number of elements it matches before it stops filtering.
Upvotes: 2
Views: 73
Reputation: 460208
I assume that you've not understood linq's deferred execution. Your first approach does exactly what you want:
list.Where(x => x == 2).Take(3)
It checks every item but just until it has found three items matching the predicate.
Have a look at Eric Lipperts answer on my question since he explains it very well: https://stackoverflow.com/a/10110269/284240
This is also worth reading: http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx
Upvotes: 8