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

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

    Here's a solution I just came up with for this problem

    Original code:

    int index=0;
    foreach (var item in enumerable)
    {
        blah(item, index); // some code that depends on the index
        index++;
    }
    

    Updated code

    enumerable.ForEach((item, index) => blah(item, index));
    

    Extension Method:

        public static IEnumerable ForEach(this IEnumerable enumerable, Action action)
        {
            var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void
            enumerable.Select((item, i) => 
                {
                    action(item, i);
                    return unit;
                }).ToList();
    
            return pSource;
        }
    

提交回复
热议问题