有没有办法在C#中的LINQ Where方法中捕获索引值?

Dav*_*ith 6 c# linq

我的下面的C#代码显然是一个hack,那么如何捕获Where方法中的索引值?

     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
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 4

Where方法返回该项目是否应包含在结果中。该函数无法以合理的方式提供更多信息(它可以捕获局部变量并用它做一些事情,但这将是可怕的)。

如果您希望最终结果中包含索引,则需要创建一个包含该索引的投影。如果您希望最终结果中包含原始索引,则需要将该投影放在任何Where子句之前。

这是一个例子:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

{ 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 }
Run Code Online (Sandbox Code Playgroud)