私は次のような辞書を持っています:
Dictionary<String, List<String>>
test1 : 1,3,4,5
test2 : 2,3,6,7
test3 : 2,8
LINQおよびLINQ拡張機能を使用してすべての値のカウントを取得するにはどうすればよいですか?
私は次のような辞書を持っています:
Dictionary<String, List<String>>
test1 : 1,3,4,5
test2 : 2,3,6,7
test3 : 2,8
LINQおよびLINQ拡張機能を使用してすべての値のカウントを取得するにはどうすればよいですか?
あなたが持っているとしましょう:
Dictionary<String, List<String>> dict = ...
リストの数が必要な場合は、次のように簡単です。
int result = dict.Count;
すべてのリスト内のすべての文字列の合計数が必要な場合:
int result = dict.Values.Sum(list => list.Count);
すべてのリスト内のすべての個別の文字列の数が必要な場合:
int result = dict.Values
.SelectMany(list => list)
.Distinct()
.Count();
どうですか
yourdictionary.Values.Sum(l => l.Count);
各アイテムを別々に数えたい場合:
dict.Values.SelectMany(s => s).GroupBy(s => s)
.Select(g => new {Value = g.First(), Count = g.Count});
サンプルを使用すると、次のものが得られます。
"1", 1; "3", 2; "4"、1; "5"、1、"6"、1; "7"、1; "8"、1