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


当前回答

正如在这个答案中已经指出的,KeyValuePair<TKey,TValue>实现了一个从.NET Core 2.0、.NET Standard 2.1和.NET Framework 5.0(预览版)开始的解构方法。

这样,就可以以KeyValuePair不可知的方式遍历字典:

var dictionary = new Dictionary<int, string>();

// ...

foreach (var (key, value) in dictionary)
{
    // ...
}

其他回答

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

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

如果您试图在C#中使用通用字典,就像在另一种语言中使用关联数组一样:

foreach(var item in myDictionary)
{
  foo(item.Key);
  bar(item.Value);
}

或者,如果只需要遍历密钥集合,请使用

foreach(var item in myDictionary.Keys)
{
  foo(item);
}

最后,如果你只对价值观感兴趣:

foreach(var item in myDictionary.Values)
{
  foo(item);
}

(请注意,var关键字是可选的C#3.0及以上版本的特性,您也可以在此处使用键/值的确切类型)

var dictionary = new Dictionary<string, int>
{
    { "Key", 12 }
};

var aggregateObjectCollection = dictionary.Select(
    entry => new AggregateObject(entry.Key, entry.Value));

我只想加上我的2美分,因为大多数答案都与foreach循环有关。请查看以下代码:

Dictionary<String, Double> myProductPrices = new Dictionary<String, Double>();

//Add some entries to the dictionary

myProductPrices.ToList().ForEach(kvP => 
{
    kvP.Value *= 1.15;
    Console.Writeline(String.Format("Product '{0}' has a new price: {1} $", kvp.Key, kvP.Value));
});

尽管这增加了一个额外的“.ToList()”调用,但性能可能会略有改善(正如这里指出的foreach vs someList.foreach(){}),尤其是在处理大型词典和并行运行时,没有选择/根本不会产生效果。

此外,请注意,您无法在foreach循环中为“Value”属性赋值。另一方面,您也可以操作“Key”,可能会在运行时遇到麻烦。

当您只想“读取”键和值时,也可以使用IEnumerable.Select()。

var newProductPrices = myProductPrices.Select(kvp => new { Name = kvp.Key, Price = kvp.Value * 1.15 } );

我将利用.NET 4.0+的优势,为最初接受的问题提供更新的答案:

foreach(var entry in MyDic)
{
    // do something with entry.Value or entry.Key
}