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


当前回答

如果您试图在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及以上版本的特性,您也可以在此处使用键/值的确切类型)

其他回答

我写了一个扩展来遍历字典。

public static class DictionaryExtension
{
    public static void ForEach<T1, T2>(this Dictionary<T1, T2> dictionary, Action<T1, T2> action) {
        foreach(KeyValuePair<T1, T2> keyValue in dictionary) {
            action(keyValue.Key, keyValue.Value);
        }
    }
}

然后你可以打电话

myDictionary.ForEach((x,y) => Console.WriteLine(x + " - " + y));

C#7.0引入了解构器,如果您正在使用.NET Core 2.0+应用程序,那么结构KeyValuePair<>已经为您提供了一个解构器()。因此,您可以做到:

var dic = new Dictionary<int, string>() { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
foreach (var (key, value) in dic) {
    Console.WriteLine($"Item [{key}] = {value}");
}
//Or
foreach (var (_, value) in dic) {
    Console.WriteLine($"Item [NO_ID] = {value}");
}
//Or
foreach ((int key, string value) in dic) {
    Console.WriteLine($"Item [{key}] = {value}");
}

我在MSDN上DictionaryBase类的文档中找到了此方法:

foreach (DictionaryEntry de in myDictionary)
{
     //Do some stuff with de.Value or de.Key
}

这是我唯一能够在从DictionaryBase继承的类中正确运行的一个。

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

我只想加上我的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 } );