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


当前回答

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

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));

其他回答

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

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

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

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}");
}

正如在这个答案中已经指出的,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)
{
    // ...
}

字典<TKey, TValue>它是c#中的一个泛型集合类,它以键值格式存储数据。键值必须是唯一的,不能为null,而值可以是重复的和null。由于字典中的每个项都被视为KeyValuePair<TKey, TValue>表示键及其值的结构。因此我们应该采用元素类型KeyValuePair<TKey, 元素迭代期间的TValue>。下面是示例。

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"One");
dict.Add(2,"Two");
dict.Add(3,"Three");

foreach (KeyValuePair<int, string> item in dict)
{
    Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

使用C#7,将此扩展方法添加到解决方案的任何项目中:

public static class IDictionaryExtensions
{
    public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(
        this IDictionary<TKey, TValue> dict)
    {
        foreach (KeyValuePair<TKey, TValue> kvp in dict)
            yield return (kvp.Key, kvp.Value);
    }
}

使用这个简单的语法

foreach (var(id, value) in dict.Tuples())
{
    // your code using 'id' and 'value'
}

或者这个,如果你喜欢的话

foreach ((string id, object value) in dict.Tuples())
{
    // your code using 'id' and 'value'
}

代替传统的

foreach (KeyValuePair<string, object> kvp in dict)
{
    string id = kvp.Key;
    object value = kvp.Value;

    // your code using 'id' and 'value'
}

扩展方法将IDictionary<TKey,TValue>的KeyValuePair转换为强类型元组,允许您使用这种新的舒适语法。

它只将所需的字典条目转换为元组,因此不会将整个字典转换为元组。因此,不存在与此相关的性能问题。

与直接使用KeyValuePair相比,调用扩展方法来创建元组的成本很低,如果您要将KeyValuePail的财产Key和Value分配给新的循环变量,那么这应该不是问题。

实际上,这种新语法非常适合大多数情况,除了低级别的超高性能场景,在这种情况下,您仍然可以选择不在特定位置使用它。

看看这个:MSDN博客-C#7中的新功能