How do I get the key of the current element in a foreach
loop in C#?
For example:
foreach ($array as $key => $value)
{
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