繁体   English   中英

Lambda表达式+词典:已经添加了具有相同键的项

[英]Lambda expression + Dictionary: An item with the same key has already been added

我有这样的事情:

var result = new MyList()
{
    Items = new List<Item>(),
    ...
}

其中每个项目都有一个itemType属性,我需要一个Dictionary<itemType, count> ,它返回列表中每个itemType的计数。 我这样做:

var res = new Dictionary<itemType, int>();
res = result.Items.ToDictionary(a => a.itemType,
                                a=> result.Items.Count(i => i.itemType== a.itemType));}

但是我收到此错误“因为已经在列表中添加了多个具有相同键的项目,因为我的列表中有多个具有相同类型的项目,我该如何分组?

您可以缩短它,但是无论如何:

var groups = result.Items.GroupBy(r => r.itemType).Select(g => new { id = g.Key, count = g.Count() });
var res = new Dictionary<itemType, int>();
res = groups.ToDictionary(a => a.id, a=>a.count);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM