Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain System.Linq.Enumerable.Where(Func<T, int, bool> predicate)

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?

like image 455
Water Cooler v2 Avatar asked Dec 28 '22 10:12

Water Cooler v2


1 Answers

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.
like image 127
Noldorin Avatar answered Feb 03 '23 08:02

Noldorin