【发布时间】:2018-08-13 05:39:21
【问题描述】:
如何在单行 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;
}
【问题讨论】:
-
items.GroupBy(e => e).ToDictionary<string, int>(e => e,e => e.Count());怎么不起作用? -
items.GroupBy(e => e).ToDictionary(k => k.Key, v => v.Count());。你需要分组的Key