转换列表< T>到词典与策略 [英] Convert List<T> to Dictionary with strategy

查看:103
本文介绍了转换列表< T>到词典与策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 私人类DTO 
{
public string Name {get ;组; }
public int Count {get;组;
}

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

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

现在我的要求是我需要从dtoCollection创建一个Dictionary,其Key是 Name 字段,值为计数字段的总和。



例如,如果将上述dtoCollection转换为Dictionary,则该条目应为像


Key =test,Value =5


其中通过总结名称字段相同的计数字段获得价值

解决方案

我想这将做你所需要的:

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


I have List < DTO > where DTO class looks like this,

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

I create objects and add it to List.

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

Now my requirement is I need to create an Dictionary from the dtoCollection whose Key is Name field and value is Sum of Count fields.

For example, if you convert the above dtoCollection to Dictionary, the entry should be like

Key = "test" , Value = "5"

Where Value is obtained from summing up the Count fields whose Name fields are same

解决方案

I guess this will do what you need:

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

这篇关于转换列表&lt; T&gt;到词典与策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆