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


当前回答

在.NET Framework 4.7中,可以使用分解

var fruits = new Dictionary<string, int>();
...
foreach (var (fruit, number) in fruits)
{
    Console.WriteLine(fruit + ": " + number);
}

要使此代码在较低的C#版本上运行,请添加System.ValueTuple NuGet包并在某处编写

public static class MyExtensions
{
    public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple,
        out T1 key, out T2 value)
    {
        key = tuple.Key;
        value = tuple.Value;
    }
}

其他回答

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

除了在使用

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

or

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

最完整的是以下内容,因为您可以从初始化中看到字典类型,kvp是KeyValuePair

var myDictionary = new Dictionary<string, string>(x);//fill dictionary with x

foreach(var kvp in myDictionary)//iterate over dictionary
{
    // do something with kvp.Value or kvp.Key
}

从C#7开始,您可以将对象分解为变量。我认为这是遍历字典的最佳方式。

例子:

在KeyValuePair<TKey,TVal>上创建一个扩展方法,对其进行解构:

public static void Deconstruct<TKey, TVal>(this KeyValuePair<TKey, TVal> pair, out TKey key, out TVal value)
{
   key = pair.Key;
   value = pair.Value;
}

按以下方式遍历任何字典<TKey,TVal>

// Dictionary can be of any types, just using 'int' and 'string' as examples.
Dictionary<int, string> dict = new Dictionary<int, string>();

// Deconstructor gets called here.
foreach (var (key, value) in dict)
{
   Console.WriteLine($"{key} : {value}");
}

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

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

这就是你要找的吗?

迭代字典的最简单形式:

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