asp.net: как получить доступ к каждому элементу словаря без использования ключа? - PullRequest
2 голосов
/ 13 мая 2009

Я хочу получить доступ к каждому объекту моего словаря Словарь с индексом int. как это сделать.

Ответы [ 4 ]

5 голосов
/ 13 мая 2009
Dictionary<KeyType, ValueType> myDictionary = . . .


foreach(KeyValuePair<KeyType, ValueType> item in myDictionary)
{
   Console.WriteLine("Key={0}: Value={1}", item.Key, item.Value);
}
1 голос
/ 13 мая 2009

Мой любимый подход такой (хотя я думаю, что любое решение, данное до сих пор, поможет вам):

// set up the dictionary
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("A key", "Some value");
dictionary.Add("Another key", "Some other value");

// loop over it
Dictionary<string, string>.Enumerator enumerator = dictionary.GetEnumerator();
while (enumerator.MoveNext())
{
    Console.WriteLine(enumerator.Current.Key + "=" + enumerator.Current.Value);
}
1 голос
/ 13 мая 2009

Или если вы работаете в Visual Studio 2008, вы можете:

foreach(var item in myDictionary)
{
   . . . 
}
1 голос
/ 13 мая 2009

Вы можете использовать цикл foreach, как показано ниже:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("key1", "value2");
dict.Add("key2", "value");
foreach (KeyValuePair<string, string> item in dict)
   Console.WriteLine(item.Key + "=" + item.Value);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...