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

标签 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;
}

最佳答案

您需要分组的Key

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

关于c# - Lambda 计算 IEnumerable 中字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51815776/

相关文章:

c# - C# 未初始化的变量危险吗?

jquery - 使用 AJAX 将模型从部分 View 传递到 Controller 的最佳方法?

asp.net - 禁止使用 jquery 在所有输入文本框中输入少量字符,例如 .'<' 、 '>'

asp.net - 如何分析 ASP.NET/IIS 管道

c# - 如何加密一串文本,即使值相同,每次加密的字符串都不同

c# - Azure 上的 Cyber​​Source

c# - Web Api 方法接受字符串、整数、字母数字

c# - 如何从模型列表中的模型分配值

c# - 在 WPF 中为组合框设置默认名称

c# - 调试 WP7 崩溃