2013-07-02 3 views
0

목록에 저장된 요소의 빈도를 가져 오려고합니다.C에서 목록에서 요소의 빈도를 얻는 방법 #

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

자바에서 당신은 다음과 같은 방법을 수행 할 수 있습니다

내 목록

ID 
1 
2 
1 
3 
3 
4 
4 
4 

에 다음 ID 년대를 저장하고 나는 다음과 같은 출력을합니다.

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

당신은 키가 ID이고 값이 ID가 나타납니다 횟수입니다 곳은 Dictionary 객체를 생성합니다 LINQ

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

를 사용할 수 있습니다.

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); 
} 
관련 문제