Getting the array key in a 'foreach' loop

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

    With DictionaryEntry and KeyValuePair:

    Based on
    MSDN

    IDictionary openWith = new Dictionary()
    {
       { "txt", "notepad.exe" }
       { "bmp", "paint.exe" }
       { "rtf", "wordpad.exe" }
    };
    
    foreach (DictionaryEntry de in openWith)
    {
        Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
    }
    
    // also
    
    foreach (KeyValuePair de in openWith)
    {
        Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
    }
    

    Releated SO question: KeyValuePair VS DictionaryEntry

提交回复
热议问题