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


当前回答

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

其他回答

字典<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);
}
foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

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

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

一般来说,在没有特定上下文的情况下要求“最佳方式”就像要求什么是最好的颜色?

一方面,有很多颜色,没有最好的颜色。这取决于需求,也常常取决于口味。

另一方面,有很多方法可以在C#中迭代字典,没有最好的方法。这取决于需求,也常常取决于口味。

最直接的方式

foreach (var kvp in items)
{
    // key is kvp.Key
    doStuff(kvp.Value)
}

如果您只需要值(允许将其称为item,比kvp.value更可读)。

foreach (var item in items.Values)
{
    doStuff(item)
}

如果您需要特定的排序顺序

一般来说,初学者对词典的列举顺序感到惊讶。

LINQ提供了一种简洁的语法,允许指定顺序(以及许多其他事情),例如:

foreach (var kvp in items.OrderBy(kvp => kvp.Key))
{
    // key is kvp.Key
    doStuff(kvp.Value)
}

同样,您可能只需要值。LINQ还提供了一个简洁的解决方案:

直接迭代值(允许将其称为item,比kvp.value更可读)但按按键排序

这里是:

foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
    doStuff(item)
}

从这些示例中可以看到更多真实世界的用例。如果您不需要特定的订单,只需坚持“最直接的方式”(见上文)!