【问题标题】:Convert List<T> to Dictionary with strategy使用策略将 List<T> 转换为 Dictionary
【发布时间】:2012-11-14 11:24:43
【问题描述】:

我有 List,其中 DTO 类看起来像这样,

 private class DTO
    {
        public string Name { get; set; }
        public int Count { get; set; }
    }

我创建对象并将其添加到列表中。

var dto1 = new DTO { Name = "test", Count = 2 };
var dto2 = new DTO { Name = "test", Count = 3 };
var dtoCollection = new List<DTO> {dto1, dto2};

现在我的要求是我需要从 dtoCollection 创建一个字典,其键是 Name 字段,值是 Count 字段的总和。

例如,如果将上面的 dtoCollection 转换为 Dictionary,条目应该是这样的

键=“测试”,值=“5”

Value 是通过将 Name 字段相同的 Count 个字段相加得到的

【问题讨论】:

    标签: c# linq dictionary lambda


    【解决方案1】:

    我想这会满足你的需要:

    dtoCollection.GroupBy(x => x.Name).ToDictionary(x => x.Key, x => x.Sum(y => y.Count))
    

    【讨论】:

    • 我的想法完全正确。并且不要忘记包含System.Linq
    【解决方案2】:

    下面是 linq 查询

    var dict = dtoCollection.GroupBy(x=>x.Name).ToDictionary(x=>x.Key, x=>x.Select(y=>y.Count).Sum());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 2011-10-27
      相关资源
      最近更新 更多