如何在单行 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/