【问题标题】:Lambda expression + Dictionary: An item with the same key has already been addedLambda 表达式 + 字典:已添加具有相同键的项
【发布时间】:2014-01-17 02:25:03
【问题描述】:

我有这样的事情:

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

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

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

但我收到此错误“已添加具有相同键的项目”,因为我的列表中当然有多个具有相同类型的项目,我该如何做一个组由或不同的???

【问题讨论】:

标签: c# asp.net-mvc-4 lambda


【解决方案1】:

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

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);

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2013-03-18
    • 2023-01-11
    • 2011-01-07
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多