如何使用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
相关产品推荐
相关产品推荐

