The Where method only returns whether the element should be included in the result or not. A function cannot provide more information in a reasonable way (it can capture a local variable and do something like this with it, but that would be awful).
If you need an index in the end result, you need to create a projection that includes this index. If you want the original index to be the final result, you need to put this projection in front of any Where clauses.
Here is an example of this:
using System; using System.Collections.Generic; using System.Linq; public class Test { static void Main() { IEnumerable<char> letters = "aBCdEFghIJklMNopQRsTUvWyXZ"; var query = letters.Select((c, i) => new { Char=c, OriginalIndex=i }) .Where(x => char.IsLower(x.Char)) .Select((x, i) => new { x.Char, x.OriginalIndex, FinalIndex=i}); foreach (var result in query) { Console.WriteLine(result); } } }
Results:
{ Char = a, OriginalIndex = 0, FinalIndex = 0 } { Char = d, OriginalIndex = 3, FinalIndex = 1 } { Char = g, OriginalIndex = 6, FinalIndex = 2 } { Char = h, OriginalIndex = 7, FinalIndex = 3 } { Char = k, OriginalIndex = 10, FinalIndex = 4 } { Char = l, OriginalIndex = 11, FinalIndex = 5 } { Char = o, OriginalIndex = 14, FinalIndex = 6 } { Char = p, OriginalIndex = 15, FinalIndex = 7 } { Char = s, OriginalIndex = 18, FinalIndex = 8 } { Char = v, OriginalIndex = 21, FinalIndex = 9 } { Char = y, OriginalIndex = 23, FinalIndex = 10 }
Jon skeet
source share