C# 对于每个获取行索引
是否有一种方法可以让每个人都获得行索引 例如:C# 对于每个获取行索引,c#,.net-3.5,extension-methods,C#,.net 3.5,Extension Methods,是否有一种方法可以让每个人都获得行索引 例如: 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 { Inde
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
}
publicstaticvoidforeach(此IEnumerable源代码,Action del){
int i=0;
foreach(源中的var cur){
del(cur,i);
i++;
}
}
数字。ForEach((x,i)=>
{
//x是值,i是索引
}
这不会在“定义本地并手动递增”解决方案上增加太多内容。您不想这样做有什么特殊原因吗?请尝试以下方法
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
}
publicstaticvoidforeach(此IEnumerable源代码,Action del){
int i=0;
foreach(源中的var cur){
del(cur,i);
i++;
}
}
数字。ForEach((x,i)=>
{
//x是值,i是索引
}
这并没有在“定义本地并手动递增”解决方案的基础上增加太多内容。您不想这样做有什么特别的原因吗?如果您要坚持使用foreach循环,这可能是最简单的方法。没有任何级别,但我认为这是最好的方法
int rowIndex = 0;
foreach (int a in numbers)
{
rowIndex++; // You could of course inline this wherever rowIndex first
// gets used, and then simply reference rowIndex (without
// the increment) later.
// ...
}
但一旦开始这样做,可能最好还是使用普通的for循环(除非您不能这样做,因为集合只实现
IEnumerable
,而不是IList
/ICollection
)如果你要坚持foreach循环,这可能是最简单的方法。没有任何级别,但我认为这是保持静止的最好方法
int rowIndex = 0;
foreach (int a in numbers)
{
rowIndex++; // You could of course inline this wherever rowIndex first
// gets used, and then simply reference rowIndex (without
// the increment) later.
// ...
}
但一旦开始这样做,可能最好还是使用普通的for循环(除非您不能这样做,因为集合只实现
IEnumerable
,而不是IList
/ICollection
).这项工作更多地体现了询问者想要的语法风格,但对我来说,这似乎有点难看,与增加局部值相比,并没有真正增加额外的值。@Noldorin,我同意,但这是用户要求的。我会添加一些qualifications@JaredPar:是的,的确,询问者似乎确实想要这样的东西。无论如何,这是一个很好的答案,现在可以选择(稍微好一点)还有附加条件。这项工作更多地体现了询问者想要的语法风格,尽管对我来说这似乎有点难看,与增加局部值相比,并没有真正增加额外的值。@Noldorin,我同意,但这是用户要求的。我会添加一些qualifications@JaredPar当前位置是的,的确,询问者似乎确实想要som是这样的。不管怎样,这是一个很好的答案,有了替代方案(稍微好一点)和附加的条件。重复的?可能的重复的?可能的重复的