2014-01-17 41 views
0

我有这样的事情:Lambda表达式+词典:具有相同键的项已被添加

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

但我发现了这个错误,当然怎么一回事,因为有几个项目在我的列表中的同类型的“的使用相同的密钥已经被添加项目”,怎么能我做一个小组或一个明显的?

+1

http://stackoverflow.com/questions/1300088/distinct-with-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); 
相关问题