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

相关推荐
唐青枫4 小时前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫1 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6251 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902111 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠2 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫4 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech4 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf6 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6256 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech6 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf