本文主要介绍.NET Core(C#),通过循环遍历字典的几种常用方法,以实现的示例代码。

1、通过KeyValuePair<TKey,TValue>类型遍历

 var myDictionary=  new Dictionary<string, string>
            {
                {"a","n" },
                {"b","n" },
                {"c","n" },
                {"d","n" },
                {"e","n" },
                {"f","n" },
            };
   foreach (KeyValuePair<string, string> entry in myDictionary)
   {
    Console.WriteLine($"key={entry.Key},value={entry.Value}");
   }

2、使用var实现遍历

 var myDictionary=  new Dictionary<string, int>
{
    {"a",11 },
    {"b",22 },
    {"c",33 },
    {"d",44 },
    {"e",55 },
    {"f",66 },
};
foreach (var kvp in myDictionary)
{
    // key is kvp.Key
    Console.WriteLine($"{kvp.Key} : {kvp.Value}");
}
//仅遍历值
foreach (var item in myDictionary.Values)
{
    Console.WriteLine($"value:{item}");
}
//通过key排序后遍历key value
foreach (var kvp in myDictionary.OrderBy(kvp => kvp.Key))
{
    // key is kvp.Key
    Console.WriteLine($"{kvp.Key} : {kvp.Value}");
}
//通过key排序后遍历value
foreach (var item in myDictionary.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
    Console.WriteLine($"value:{item}");
}

3、var (key, value)方式将对象解构(deconstruct)成变量实现

从C#7.0开始,可以将对象解构为变量。这是迭代字典的很好的方法。

1) 创建一个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;
}

注意:此扩展方法要在非泛型静态中定义。

2) Dictionary<TKey, TVal>以下列方式遍历任何对象

// Dictionary可以是任何类型,只使用'int'和'string'作为例子。
Dictionary<int, string> dict = new Dictionary<int, string>();
// Deconstructor gets called here.
foreach (var (key, value) in dict)
{
   Console.WriteLine($"{key} : {value}");
}

相关文档.NET(C#)遍历(for,foreach,while)字典(Dictionary)的几种方法