简体   繁体   English

使用linq将重复数据分组并计算到字典中

[英]group and count duplicates to a dictionary with linq

with the following list: 具有以下列表:

a
a
b
b
b
c

I would like to make, using linq, a dictionary that contains: 我想使用linq制作一个包含以下内容的字典:

a => 2
b => 3
c => 1

for now I have: 现在我有:

var Q = (from l in List
        group l by l into g
        let Count = g.Count()
        select new { Key = g.Key, Value = Count})

How do I turn this to a dictionary? 如何将其变成字典?

Edit: I changed the last line to: 编辑:我将最后一行更改为:

select new Dictionary<string, int> { g.Key, Count });

but I still don't have the right syntax 但我仍然没有正确的语法

Just slap a ToDictionary after a GroupBy . GroupBy之后拍一本ToDictionary

var counts = List.GroupBy(l => l)
    .ToDictionary(grp => grp.Key, grp => grp.Count());

You are very close to solution in fact. 实际上,您非常接近解决方案。 You can also solve it such; 您也可以这样解决;

    var query =
        from q in list
        group q by q into t
        select new
        {
            Key = t.Key,
            Value = t.Count()
        }; 
    var dict = query.ToDictionary(x => x.Key, x => x.Value);

This way Works to me 这样对我有效

List<string> vs = new List<string> { "a", "a", "b", "a", "b", "b" };

        var output = vs.GroupBy(word => word).OrderByDescending(group => group.Count()).Select(group => group.Key);

        foreach (var item in output)
        {
            Console.WriteLine(item + "=>" + item.Count() );
        }

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

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