Getting the array key in a 'foreach' loop

前端 未结 9 593
别跟我提以往
别跟我提以往 2021-02-03 22:42

How do I get the key of the current element in a foreach loop in C#?

For example:

PHP

foreach ($array as $key => $value)
{
             


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-03 23:31

    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;
        }
    

提交回复
热议问题