📜  c# 遍历字典 - C# (1)

📅  最后修改于: 2023-12-03 15:13:52.914000             🧑  作者: Mango

C# 遍历字典

在 C# 中,字典(Dictionary)是一种常用的数据结构。但在处理字典数据时,有时需要对字典进行遍历。本文将介绍 C# 中遍历字典的方法。

foreach 循环

使用 foreach 循环是遍历字典的最简单方法。它可以用于遍历字典中的键值对(Key-Value Pair)。具体代码如下:

Dictionary<string, int> dict = new Dictionary<string, int>();

dict.Add("a", 1);
dict.Add("b", 2);
dict.Add("c", 3);

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

运行结果如下:

a: 1
b: 2
c: 3

以上代码中,使用 KeyValuePair<string, int> 定义了键值对类型,通过 foreach 循环遍历字典元素并输出了它的键和值。

使用字典的 Keys 和 Values 属性

除了 foreach 循环外,C# 还提供了字典的 Keys 和 Values 属性,可以用于遍历字典的键和值。具体代码如下:

Dictionary<string, int> dict = new Dictionary<string, int>();

dict.Add("a", 1);
dict.Add("b", 2);
dict.Add("c", 3);

foreach (string key in dict.Keys)
{
    Console.WriteLine(key);
}

foreach (int value in dict.Values)
{
    Console.WriteLine(value);
}

运行结果如下:

a
b
c
1
2
3

以上代码中,分别使用了 dict.Keys 和 dict.Values 属性来遍历字典的键和值,并输出了它们的内容。

LINQ

除了以上两种方法,还可以使用 LINQ 查询表达式来遍历字典。具体代码如下:

Dictionary<string, int> dict = new Dictionary<string, int>();

dict.Add("a", 1);
dict.Add("b", 2);
dict.Add("c", 3);

var query = from kv in dict
            where kv.Value > 1
            select kv;

foreach (var item in query)
{
    Console.WriteLine(item.Key + ": " + item.Value);
}

运行结果如下:

b: 2
c: 3

以上代码中,使用了 LINQ 查询表达式来筛选字典中值大于 1 的键值对,并遍历输出其内容。

小结

本文介绍了 C# 中遍历字典的三种方法:使用 foreach 循环、使用字典的 Keys 和 Values 属性,以及使用 LINQ 查询表达式。不同的方法适用于不同的开发场景,需要自行选择使用。