I have a List<String> Fruits
that stores a list of fruits the user enters.
For example 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. Any hints would be greatly appreciated
You may GroupBy the friuit name and take count of each group:
Fruits.GroupBy(x => x).Select(x => new {Name = x.Key, Count = x.Count()});
Utilise GroupBy
followed with ToDictionary
:
Dictionary<string, int> result = fruits.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.