How do you get the index of the current iteration of a foreach loop?

后端 未结 30 2091
刺人心
刺人心 2020-11-22 07:05

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 iter

30条回答
  •  无人共我
    2020-11-22 07:24

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

    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:

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

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

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

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

    You can also eliminate the item. by using automatic destructuring:

      foreach ((MyType value, Int32 i) in Model.Select((value, i) => ( value, i ))) {
    1. @value
    2. }

提交回复
热议问题