我看到了一些不同的方法来迭代C#中的字典。有标准的方法吗?


当前回答

有很多选择。我个人最喜欢的是KeyValuePair

Dictionary<string, object> myDictionary = new Dictionary<string, object>();
// Populate your dictionary here

foreach (KeyValuePair<string,object> kvp in myDictionary)
{
     // Do some interesting things
}

您也可以使用键和值集合

其他回答

foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

迭代字典的最简单形式:

foreach(var item in myDictionary)
{ 
    Console.WriteLine(item.Key);
    Console.WriteLine(item.Value);
}

如果您希望在默认情况下迭代值集合,我相信您可以实现IEnumerable<>,其中T是字典中值对象的类型,“this”是字典。

public new IEnumerator<T> GetEnumerator()
{
   return this.Values.GetEnumerator();
}

有时,如果只需要枚举值,请使用字典的值集合:

foreach(var value in dictionary.Values)
{
    // do something with entry.Value only
}

本帖报道称,这是最快的方法:http://alexpinsker.blogspot.hk/2010/02/c-fastest-way-to-iterate-over.html

我想说foreach是标准的方法,尽管这显然取决于你想要什么

foreach(var kvp in my_dictionary) {
  ...
}

这就是你要找的吗?