【问题标题】:Count number of duplicate values in a list<string> and store in dictionary [duplicate]计算 list<string> 中重复值的数量并存储在字典中 [duplicate]
【发布时间】:2015-08-19 17:00:10
【问题描述】:

我有一个字符串列表,在这个列表中有一些重复两次或更多次的字符串。

我想计算它们并将它们添加到字典中,如下所示:

List<string> lst = { 'A' , 'B' , 'B' , 'c' , 'c' , 'c' };

它会像这样进入字典:

A , 1
B , 2
c , 3

我该怎么做?!

【问题讨论】:

    标签: c# string list dictionary duplicates


    【解决方案1】:
    var dict = lst.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
    

    如果您想以不区分大小写的方式进行操作

    var dict = lst.GroupBy(x => x, StringComparer.InvariantCultureIgnoreCase )
                  .ToDictionary(x => x.Key, x => x.Count());
    

    【讨论】:

    • 快速简单,谢谢。
    【解决方案2】:

    类似这样的:

      List<Char> lst = new {  // Note "Char"
        'A' , 'B' , 'B' , 'c' , 'c' , 'c' };
    
      var dictionary = list
        .GroupBy(item => item)
        .ToDictionary(chunk => chunk.Key,
                      chunk => chunk.Count());
    

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 2021-11-21
      • 2016-06-11
      相关资源
      最近更新 更多