11

私は次のような辞書を持っています:

Dictionary<String, List<String>>

test1 : 1,3,4,5
test2 : 2,3,6,7
test3 : 2,8

LINQおよびLINQ拡張機能を使用してすべての値のカウントを取得するにはどうすればよいですか?

4

3 に答える 3

46

あなたが持っているとしましょう:

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();
于 2012-08-14T14:34:12.580 に答える
6

どうですか

yourdictionary.Values.Sum(l => l.Count);
于 2012-08-14T14:34:44.390 に答える
0

各アイテムを別々に数えたい場合:

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

于 2012-08-14T14:38:41.070 に答える