在C#中遍历字典(Dictionary)是一个常见的操作。字典是一种键值对集合,通常使用Dictionary<TKey, TValue>
泛型类来实现。遍历字典的主要方法是通过迭代其键值对。这里有几种常用的遍历字典的方式:
1. 使用 foreach 循环
最简单的方法是使用foreach
循环遍历字典的所有键值对:
csharp
深色版本
1using System;
2using System.Collections.Generic;
3
4class Program
5{
6 static void Main()
7 {
8 Dictionary<string, int> myDict = new Dictionary<string, int>
9 {
10 { "one", 1 },
11 { "two", 2 },
12 { "three", 3 }
13 };
14
15 foreach (var item in myDict)
16 {
17 Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
18 }
19 }
20}
在这个例子中,foreach
循环会迭代字典中的每一个键值对。item.Key
表示键,item.Value
表示对应的值。
2. 分别获取键和值
如果你只想遍历键或值,可以分别使用.Keys
和.Values
属性:
csharp
深色版本
1foreach (var key in myDict.Keys)
2{
3 Console.WriteLine($"Key: {key}, Value: {myDict[key]}");
4}
5
6foreach (var value in myDict.Values)
7{
8 Console.WriteLine($"Value: {value}");
9}
3. LINQ 查询
如果你使用的是.NET Framework 3.5 或更高版本,还可以使用LINQ查询来遍历字典:
csharp
深色版本
1from entry in myDict
2select entry; // 直接获取键值对
3
4// 或者更复杂的查询
5var query = from entry in myDict
6 where entry.Value > 1
7 select entry;
8
9foreach (var item in query)
10{
11 Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
12}
4. 使用迭代器
虽然不太常见,但你也可以编写一个迭代器来遍历字典:
csharp
深色版本
1public static IEnumerable<KeyValuePair<string, int>> IterateDict(Dictionary<string, int> dict)
2{
3 foreach (var pair in dict)
4 {
5 yield return pair;
6 }
7}
8
9// 使用
10foreach (var item in IterateDict(myDict))
11{
12 Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
13}
以上就是一些基本的遍历字典的方法。选择哪种方式取决于你的具体需求和代码风格偏好。在实际开发中,使用foreach
循环是最常见的做法,因为它简洁明了。