Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

c# - 如何获取foreach循环当前迭代的索引?(How do you get the index of the current iteration of a foreach loop?)

Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?

(在C#中是否有一些我没有遇到过的稀有语言构造(例如我最近学到的一些,有些是关于Stack Overflow的)来获取代表foreach循环当前迭代的值?)

For instance, I currently do something like this depending on the circumstances:

(例如,我目前根据情况执行以下操作:)

int i = 0;
foreach (Object o in collection)
{
    // ...
    i++;
}
  ask by Matt Mitchell translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ian Mercer posted a similar solution as this on Phil Haack's blog :

(Ian Mercer在Phil Haack的博客上发布了与此类似的解决方案:)

foreach (var item in Model.Select((value, i) => new { i, value }))
{
    var value = item.value;
    var index = item.i;
}

This gets you the item ( item.value ) and its index ( item.i ) by using this overload of LINQ's Select :

(通过使用LINQ的Select这种重载,可以获取项目( item.value )及其索引( item.i ):)

the second parameter of the function [inside Select] represents the index of the source element.

(函数[inside Select]中的第二个参数表示源元素的索引。)

The new { i, value } is creating a new anonymous object .

(new { i, value }正在创建一个新的匿名对象 。)

Heap allocations can be avoided by using ValueTuple if you're using C# 7.0 or later:

(如果您使用的是C#7.0或更高版本,则可以使用ValueTuple避免堆分配:)

foreach (var item in Model.Select((value, i) => ( value, i )))
{
    var value = item.value;
    var index = item.i;
}

You can also eliminate the item.

(您也可以消除该item.)

by using automatic destructuring:

(通过使用自动解构:)

<ol>
foreach ((MyType value, Int32 i) in Model.Select((value, i) => ( value, i )))
{
    <li id="item_@i">@value</li>
}
</ol>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...