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

后端 未结 30 1680
刺人心
刺人心 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:41

    I wasn't sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even.

    string[] names = { "one", "two", "three" };
    var oddOrEvenByName = names
        .Select((name, index) => new KeyValuePair(name, index % 2))
        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
    

    This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list.

提交回复
热议问题