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

时间:2018-10-01 19:21:35

标签: c# linq

具有以下列表:

a
a
b
b
b
c

我想使用linq制作一个包含以下内容的字典:

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

现在我有:

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

如何将其变成词典?

编辑: 我将最后一行更改为:

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

但是我仍然没有正确的语法

3 个答案:

答案 0 :(得分:2)

只需在ToDictionary之后打一个GroupBy

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

答案 1 :(得分:1)

实际上,您非常接近解决方案。您也可以这样解决;

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

答案 2 :(得分:0)

这种方式对我有效

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