在使用LINQ收集统计单词单词、LINQ

2023-09-02 10:41:16 作者:月影依风

我有5个字在其中一个StringCollection对象。其中3人是重复的话。我想创建一个LINQ查询,将计算有许多独特的话是收集并输出到控制台。因此,举例来说,如果我的StringCollection有家​​,汽车,房子,狗,猫,那么就应该像这样的输出:

I have a StringCollection object with 5 words in them. 3 of them are duplicate words. I am trying to create a LINQ query that will count how many unique words are in the collection and output them to to the console. So, for example, if my StringCollection has 'House', 'Car', 'House','Dog', 'Cat', then it should output like this:


House --> 2
Car --> 1
Dog --> 1
Cat --> 1

如何创建LINQ查询要做到这一点任何想法?

Any ideas on how to create a LINQ query to do this?

推荐答案

请尝试以下

var res = from word in col.Cast<string>()
          group word by word into g
          select new { Word = g.Key, Count = g.Count() };