gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:31:42 25 4
gpt4 key购买 nike

我的以下 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

最佳答案

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);
}
}
}

结果:

{ 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 }

关于c# - 有没有办法在 C# 的 LINQ Where 方法中捕获索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/804043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com