You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Linq将对象列表转换为以唯一属性B为键的字典?

使用LINQ将对象列表转换为分组字典

完全可以通过LINQ实现这个需求,核心思路是先按B属性分组,再将分组转换为目标字典结构:

完整代码示例

// 定义A类
public class A
{
    public int B { get; set; }
    public int C { get; set; }
}

// 输入列表
List<A> input = new() {
   new A() {B=1, C=1},
   new A() {B=1, C=20},
   new A() {B=3, C=5},
   new A() {B=6, C=10},
   new A() {B=6, C=12},
   new A() {B=6, C=30}
};

// LINQ转换逻辑
Dictionary<int, List<int>> result = input
    .GroupBy(item => item.B)
    .ToDictionary(
        group => group.Key,
        group => group.Select(item => item.C).ToList()
    );

代码说明

  • GroupBy(item => item.B):将输入列表按B属性的值分组,每个分组包含所有B值相同的A对象
  • ToDictionary(...):将分组转换为字典,键为分组的B值(group.Key),值为分组中所有对象的C属性组成的列表

转换后的result结构与预期完全一致:

{
    {1, new List<int>{1, 20}},
    {3, new List<int>{5}},
    {6, new List<int>{10, 12, 30}}
}

内容的提问来源于stack exchange,提问作者OD1995

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:48:12