C# Dictionary 转换成 List

在 C# 中,将Dictionary<TKey, TValue>转换为List的方式取决于你需要List中存储的内容(键、值、键值对,或自定义类型)。以下是常见的转换方式:

1. 转换为包含键值对的List<KeyValuePair<TKey, TValue>>

Dictionary<TKey, TValue>本身实现了IEnumerable<KeyValuePair<TKey, TValue>>接口,可直接通过 LINQ 的ToList()方法转换为包含所有键值对的List。

示例代码:

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq; // 需引用此命名空间以使用ToList()

class Program
{
    static void Main()
    {
        // 定义一个Dictionary
        Dictionary<string, int> dict = new Dictionary<string, int>
        {
            {"苹果", 5},
            {"香蕉", 3},
            {"橙子", 7}
        };

        // 转换为包含键值对的List
        List<KeyValuePair<string, int>> kvpList = dict.ToList();

        // 遍历结果
        foreach (var item in kvpList)
        {
            Console.WriteLine($"键:{item.Key},值:{item.Value}");
        }
    }
}

2. 转换为仅包含键的List

通过Dictionary的Keys属性(返回所有键的集合),再调用ToList()转换为键的List。

示例代码:

csharp 复制代码
// 转换为仅包含键的List
List<string> keysList = dict.Keys.ToList();

// 遍历键
foreach (var key in keysList)
{
    Console.WriteLine("键:" + key); // 输出:苹果、香蕉、橙子
}

3. 转换为仅包含值的List

通过Dictionary的Values属性(返回所有值的集合),再调用ToList()转换为值的List。

示例代码:

csharp 复制代码
// 转换为仅包含值的List
List<int> valuesList = dict.Values.ToList();

// 遍历值
foreach (var value in valuesList)
{
    Console.WriteLine("值:" + value); // 输出:5、3、7
}

4. 转换为自定义类型的List

如果需要将键和值封装到自定义类中,可通过Select投影后再转换为List。

示例代码:

csharp 复制代码
// 定义自定义类
public class Fruit
{
    public string Name { get; set; } // 对应Dictionary的键
    public int Count { get; set; }  // 对应Dictionary的值
}

// 转换为自定义类型的List
List<Fruit> fruitList = dict.Select(kv => new Fruit
{
    Name = kv.Key,
    Count = kv.Value
}).ToList();

// 遍历自定义类型列表
foreach (var fruit in fruitList)
{
    Console.WriteLine($"水果:{fruit.Name},数量:{fruit.Count}");
}

注意事项

需引用System.Linq命名空间(using System.Linq;),否则ToList()方法无法使用。

转换后的List是原Dictionary中元素的副本(浅拷贝),修改List中的元素不会影响原Dictionary(但如果是引用类型,修改内部属性会同步)。

相关推荐
Cheng小攸8 小时前
综合实验2
网络·windows
酿情师10 小时前
Microsoft Visual C++ Build Tools 2026 下载与安装指南(Windows)
c++·windows·microsoft
影寂ldy11 小时前
C# 类和对象
开发语言·c#
z落落13 小时前
C# 构造函数(无参/有参/重载/this)+析构函数(终结器)|GC 垃圾回收
java·开发语言·c#
idolao13 小时前
ChemSketch 10安装教程 Windows版:自定义路径+轻量看图软件指南
windows
z落落13 小时前
C# 字段与属性(get/set访问器、三种属性写法、只读属性)+属性拦截例子(get动态计算 + set数据校验)
开发语言·c#
影寂ldy14 小时前
C#栈和队列
开发语言·c#
魔法阵维护师14 小时前
从零开发游戏需要学习的c#模块,第三十四章(设置界面)
学习·游戏·c#
gc_229914 小时前
学习C#调用OpenXml操作word文档的基本用法(39:学习表格类-1)
c#·word·表格·table·openxml
gc_229915 小时前
C#测试调用Net.Codecrete.QrCodeGenerator库生成二维码的基本用法
c#·二维码·qrcodegenerator