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(但如果是引用类型,修改内部属性会同步)。

相关推荐
Scout-leaf1 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530142 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
埃博拉酱3 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
mudtools3 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的3 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21883 天前
.NET 本地Db数据库-技术方案选型
windows·c#
lindexi3 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
加号33 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
tryCbest3 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅3 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑