加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 根据唯一性对列表进行分组

发布时间:2020-12-15 04:31:23 所属栏目:百科 来源:网络整理
导读:这个问题是 Convert ListT to Dictionary with strategy的略微修改版本 我有List DTO DTO类看起来像这样, private class DTO { public string Name { get; set; } public int Count { get; set; } } 我创建对象并将其添加到List. var dto1 = new DTO { Name
这个问题是 Convert List<T> to Dictionary with strategy的略微修改版本

我有List< DTO> DTO类看起来像这样,

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

我创建对象并将其添加到List.

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

现在我的要求是我需要从dtoCollection创建一个List,其中Name字段在整个List中应该是唯一的.

例如,如果将上面的dtoCollection转换为所需的List,则结果列表应如下所示:

列表< DTO>计数应为1;

列表中的对象应该是单个DTO,其名称为“test”,Count为5

其中Count是通过总结名称字段相同的所有DTO中的Count字段获得的

解决方法

var newList = dtoCollection.GroupBy(d => d.Name)
             .Select(g => new DTO(){ Name=g.Key,Count=g.Select(d => d.Count).Sum()})
             .ToList();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读