views:

152

answers:

2

I can't make any sense of the MSDN documentation for this overload of the Where method that accepts a predicate that has two arguments where the int, supposedly, represents the index of the source element, whatever that means (I thought an enumerable was a sequence and you couldn't see further than the next item, much less do any indexing on it).

Can someone please explain how to use this overload and specifically what that int in the Func is for and how it is used?

+5  A: 

The int parameter represents the index of the current item within the current iteration. Each time you call one of the LINQ extension methods, you aren't in theory guaranteed to get the items returned in the same order, but you know they're all be returned once each and thus can be assigned indices. (Well, you are guaranteed if you know the query object is a List<T> or such, but not in general.)

Example:

var result1 = myEnumerable.Where((item, index) => index < 4);
var result2 = myEnumerable.Take(4);
// result1 and result2 are equivalent.
Noldorin
Many thanks for the great explanation, Noldorin. You make an interesting observation. In what cases would you not be sure about the sequence in which the items are returned? Could you please elaborate on that?
Water Cooler v2
+4  A: 

You can't index an IEnumerable<T> in the same way you can an array, but you might be able to use the index to filter the list in some way, or possibly to index some data in another collection which will be used in the condition.

EDIT: As an example, to skip every other element you could use:

var results = sequence.Where((item, idx) => idx % 2 == 0);
Lee
Thanks, Lee. Sure, I get the point now, but still, to me personally, it doesn't seem very intuitive. I don't know what, but something appears to be awry with that interface.
Water Cooler v2