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?
Dictionaryis an unordered collection, so your task is meaningless. - Andrew NOPforeachwill change. Understand this Dictionary is an unordered collection - Andrew NOPList<KeyValuePair<int, string>>if he needs access by index, not by key (orList<MyClass>). - Andrew NOP