My following C# code is obviously a hack so how do I capture the index value in the Where method?
string[] IntArray = { "a", "b", "c", "b", "b"};
int index=0;
var query = IntArray.Where((s,i) => (s=="b")&((index=i)==i));
//"&" and "==i" only exists to return a bool after the assignment ofindex
foreach (string s in query)
{
Console.WriteLine("{0} is the original index of {1}", index, s);
}
//outputs...
//1 is the original index of b
//3 is the original index of b
//4 is the original index of b
The
Wheremethod only returns whether or not the item should be included in the result or not. The function can’t provide any more information in a sensible way (it could capture a local variable and do stuff with it, but that would be horrible).If you want the index in the final result, you’ll need to create a projection which includes that index. If you want the original index in the final result, you’ll need to put that projection before any
Whereclauses.Here’s an example of that:
Results: