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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…