[英]C# Count occurrences in List Dynamically
I have a List<String> Fruits
that stores a list of fruits the user enters. 我有一个List<String> Fruits
,它存储用户输入的水果列表。
For example Fruits = {"Apple", "Banana", "Apple", "Orange"}
例如, Fruits = {"Apple", "Banana", "Apple", "Orange"}
I would like to count the number of occurrences of each fruit. 我想计算每种水果的出现次数。
How do I go about this? 我该怎么办? I come from a python background, and to solve this I would use dictionary. 我来自python背景,要解决这个问题,我将使用字典。 Any hints would be greatly appreciated 任何提示将不胜感激
Utilise GroupBy
followed with ToDictionary
: 使用GroupBy
然后使用ToDictionary
:
Dictionary<string, int> result = fruits.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.