【问题标题】:How to get frequency of elements from List in c#如何从C#中的List中获取元素的频率
【发布时间】:2017-03-16 17:01:15
【问题描述】:

我正在尝试获取存储在列表中的元素的频率。

我将以下 ID 存储在我的列表中

ID
1
2
1
3
3
4
4
4

我想要以下输出:

ID| Count
1 | 2
2 | 1
3 | 2
4 | 3

在 java 中,您可以执行以下操作。

for (String temp : hashset) 
    {
    System.out.println(temp + ": " + Collections.frequency(list, temp));
    }

来源:http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/

如何在c#中获取列表的频率计数?

谢谢。

【问题讨论】:

    标签: c# list frequency


    【解决方案1】:

    你可以使用 LINQ

    var frequency = myList.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
    

    这将创建一个Dictionary 对象,其中键是ID,值是ID 出现的次数。

    【讨论】:

      【解决方案2】:
      using System.Linq;
      
      List<int> ids = //
      
      foreach(var grp in ids.GroupBy(i => i))
      {
          Console.WriteLine("{0} : {1}", grp.Key, grp.Count());
      }
      

      【讨论】:

        【解决方案3】:
        int[] randomNumbers =  { 2, 3, 4, 5, 5, 2, 8, 9, 3, 7 };
        Dictionary<int, int> dictionary = new Dictionary<int, int>();
        Array.Sort(randomNumbers);
        
        foreach (int randomNumber in randomNumbers) {
            if (!dictionary.ContainsKey(randomNumber))
                dictionary.Add(randomNumber, 1);
            else
                dictionary[randomNumber]++;
            }
        
            StringBuilder sb = new StringBuilder();
            var sortedList = from pair in dictionary
                                 orderby pair.Value descending
                                 select pair;
        
            foreach (var x in sortedList) {
                for (int i = 0; i < x.Value; i++) {
                        sb.Append(x.Key+" ");
                }
            }
        
            Console.WriteLine(sb);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-22
          • 2012-07-30
          • 2014-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-22
          • 1970-01-01
          相关资源
          最近更新 更多