C#遍历 dictionary

在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循环是最常见的做法,因为它简洁明了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值