2013-07-02 54 views
0

我想要獲取存儲在列表中的元素的頻率。如何從列表中獲取元素的頻率c#

我存儲以下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#中的列表的頻率計數?

謝謝。

回答

6
using System.Linq; 

List<int> ids = // 

foreach(var grp in ids.GroupBy(i => i)) 
{ 
    Console.WriteLine("{0} : {1}", grp.Key, grp.Count()); 
} 
6

您可以使用LINQ

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

其中關鍵是ID和值是時代出現的ID數這將創建一個Dictionary對象。

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