Getting the array key in a 'foreach' loop

前端 未结 9 589
别跟我提以往
别跟我提以往 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:33

    Actually you should use classic for (;;) loop if you want to loop through an array. But the similar functionality that you have achieved with your PHP code can be achieved in C# like this with a Dictionary:

    Dictionary values = new Dictionary();
    values[0] = 5;
    values[1] = 14;
    values[2] = 29;
    values[3] = 49;
    // whatever...
    
    foreach (int key in values.Keys)
    {
        Console.WriteLine("{0} is assigned to key: {1}", values[key], key);
    }
    

提交回复
热议问题