我该如何将下面的
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());
为什么不能正常工作? - Sweeperitems.GroupBy(e => e).ToDictionary(k => k.Key, v => v.Count());
. You need the grouping'sKey
- JohanP