Lambda计算IEnumerable中字符串的出现

时间:2018-08-13 05:39:22

标签: c# asp.net .net lambda

如何在一个内衬lambda表达式中重新编写下面的GetCounts()方法?请注意,它必须是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;
}

1 个答案:

答案 0 :(得分:5)

您需要分组的Key

items.GroupBy(e => e).ToDictionary(k => k.Key, v => v.Count());