Lambda计算IEnumerable中字符串出现的次数

3
我该如何将下面的GetCounts()方法重写为一行lambda表达式?请注意,它必须是一个lambda表达式(不能是LINQ)。我正在尝试像这样做,但无法弄清确切的语法:
return items.GroupBy(e => e).ToDictionary<string, int>(e => e,e => e.Count());

代码:

static void Main(string[] args)
{
    string[] colours = new string[] { "Blue", "Blue", "Green", "Red" };
    Dictionary<string, int> values = GetCounts(colours);

    foreach (KeyValuePair<string, int> v in values)
        Console.WriteLine($"{v.Key}:{v.Value}");

    //Desired output:
    //Blue:2
    //Green:1
    //Red:1
    Console.ReadKey();
}

public static Dictionary<string, int> GetCounts(IEnumerable<string> items)
{
    var counts = new Dictionary<string, int>();

    foreach (string item in items)
        counts[item] = !counts.ContainsKey(item) ? 1 : ++counts[item];

    return counts;
}

items.GroupBy(e => e).ToDictionary<string, int>(e => e,e => e.Count()); 为什么不能正常工作? - Sweeper
1
items.GroupBy(e => e).ToDictionary(k => k.Key, v => v.Count());. You need the grouping's Key - JohanP
1个回答

5
你需要分组的“Key”。
例如:
items.GroupBy(e => e).ToDictionary(k => k.Key, v => v.Count());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接