Getting the array key in a 'foreach' loop

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

    If you want to get at the key (read: index) then you'd have to use a for loop. If you actually want to have a collection that holds keys/values then I'd consider using a HashTable or a Dictionary (if you want to use Generics).

    Dictionary items = new  Dictionary();
    
    foreach (int key in items.Keys)
    {
      Console.WriteLine("Key: {0} has value: {1}", key, items[key]);
    }
    

    Hope that helps, Tyler

提交回复
热议问题