gpt4 book ai didi

c# - 对于每个获取 RowIndex

转载 作者:太空宇宙 更新时间:2023-11-03 22:27:23 25 4
gpt4 key购买 nike

有没有办法让每个人都得到行索引?

示例:

int rowIndex = 0;
foreach (int a in numbers)
{
// Manipulation
rowIndex++;
}

我想要的东西

foreach (int a in numbers)
{
a.RowIndex;
}

有什么快速的方法吗?也许使用扩展方法?

最佳答案

尝试以下操作

foreach ( var item in numbers.Select( (x,i) => new { Index = i, Value = x })) {
var index = item.Index;
var value = item.Value;
...
}

有一个 select 的重载,它向下传递项目的索引。此代码将为包含索引和值的每个项目创建一个新的匿名类型。

这里有一个替代方法,它使语法更易读。

public static void ForEach<T>(this IEnumerable<T> source, Action<T,int> del) {
int i = 0;
foreach ( var cur in source ) {
del(cur, i);
i++;
}
}

numbers.ForEach( (x,i) =>
{
// x is the value and i is the index
}

这并没有比定义本地并手动增加它的解决方案增加很多。您是否有特殊原因不想这样做?

关于c# - 对于每个获取 RowIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/843847/

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