Example:

Dictionary<int, string> dictionary = new Dictionary<int, string>(); dictionary.Add(3, "black"); dictionary.Add(4, "word"); dictionary.Add(5, "end"); //здесь нет ошибки string value = dictionary[1]; //а вот здесь ошибка //нужно получить ключ по номеру элемента int key = dictionary[1].key; 

if we turn on the foreach cycle, everything works out

 //а вот так работает int i = 0; foreach (var var in dictionary) { if (i == 1) key = var.Key; i++; } 

But I need to change the collection so I can only apply through for How to do it?

  • 2
    Dictionary is an unordered collection, so your task is meaningless. - Andrew NOP
  • 2
    there is no error here - there will be an error at the time of execution, because there is no such key in the dictionary - Andrey NOP
  • 2
    and this is how it works - this is nonsense, because if you add more elements to the dictionary or delete something from it, the order in the foreach will change. Understand this Dictionary is an unordered collection - Andrew NOP
  • 2
    Perhaps you need something like OrderedDictionary . With the usual vocabulary, the task is incorrect. - Andrew NOP
  • 3
    Perhaps the author should simply use List<KeyValuePair<int, string>> if he needs access by index, not by key (or List<MyClass> ). - Andrew NOP

1 answer 1

"There is no error" - this is not true, try running your code, catch an exception.

And you can solve the problem with Linq, for example.

  Dictionary<int, string> dictionary = new Dictionary<int, string>(); dictionary.Add(3, "black"); dictionary.Add(4, "word"); dictionary.Add(5, "end"); var value = dictionary.ElementAt(1).Value; var key = dictionary.ElementAt(1).Key;