简体   繁体   English

C#动态计数列表中的出现次数

[英]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 任何提示将不胜感激

You may GroupBy the friuit name and take count of each group: 您可以按fruiuit名称进行分组,并对每个组进行计数:

Fruits.GroupBy(x => x).Select(x => new {Name = x.Key, Count = x.Count()});

Live Demo 现场演示

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM