代码之家  ›  专栏  ›  技术社区  ›  Thomas

使用linq对字典中的重复项进行分组和计数

  •  0
  • Thomas  · 技术社区  · 6 年前

    使用以下列表:

    a
    a
    b
    b
    b
    c
    

    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 回复  |  直到 6 年前
        1
  •  2
  •   ali    6 年前

        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
  •  2
  •   juharr    6 年前

    打一巴掌就行了 ToDictionary 过了一段时间 GroupBy

    var counts = List.GroupBy(l => l)
        .ToDictionary(grp => grp.Key, grp => grp.Count());
    
        3
  •  0
  •   Abdelrhman Elsaid    6 年前

    这种方法对我有效

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