2

リストに格納されている要素の頻度を取得しようとしています。

次の 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#でリストの頻度カウントを取得するには?

ありがとう。

4

3 に答える 3

13

LINQを使用できます

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

これにより、キーがで、値が ID の出現回数であるDictionaryオブジェクトが作成されます。ID

于 2013-07-02T19:26:35.253 に答える
8
using System.Linq;

List<int> ids = //

foreach(var grp in ids.GroupBy(i => i))
{
    Console.WriteLine("{0} : {1}", grp.Key, grp.Count());
}
于 2013-07-02T19:26:23.950 に答える
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);
}
于 2017-03-16T07:40:05.820 に答える