简体   繁体   English

使用LINQ C#获取最多出现的字符串值

[英]Getting most occured string value using LINQ C#

I have a list of strings which I group by their occurrence in the list like following (where key is the list of those strings): 我有一个字符串列表,按它们在列表中的出现情况进行分组,如下所示(其中键是这些字符串的列表):

  mostCommonKeywords = key.GroupBy(v => v)
                            .OrderByDescending(g => g.Count()) // here I get the count number
                            .Select(g => g.Key)
                            .Distinct()
                            .ToList();

The thing I want to do now is when they are sorted out, I wanna get their count, since LINQ can clearly distinguish their number and sort them out... How can I get the count occurrence of each string in the list now ??? 我现在想做的是对它们进行排序后,我希望得到它们的计数,因为LINQ可以清楚地区分它们的编号并对其进行分类...我现在如何才能获得列表中每个字符串的计数出现率? ?

Edit: 编辑:

Let's say I have count values that look like this: 假设我的计数值如下所示:

124
68
55
48
32
19
13
10

I cannot simply Add 1 of this value into a variable called "Count" as @octavioccl suggested. 我不能像建议的@octavioccl那样简单地将此值中的1添加到名为“ Count”的变量中。 I clearly have to store them into some kind of list or something... 我显然必须将它们存储在某种列表或其他内容中...

Using the Select and projecting in an anonymous type : 使用Select并以匿名类型投影:

 var result=key.GroupBy(v => v)
               .Select(g => new {g.Key, Count=g.Count()})
               .OrderByDescending(e => e.Count) 
            // .Distinct()// Don't need this call
               .ToList();

Update 更新资料

You can also project your query using a DTO: 您还可以使用DTO投影查询:

public class CustomDTO
{
  public string Key{get;set;} // Change the type in case you need to
  public int Count{get;set;}
}

So, your query would be: 因此,您的查询将是:

 var result=key.GroupBy(v => v)
               .Select(g => new CustomDTO{Key=g.Key, Count=g.Count()})
               .OrderByDescending(e => e.Count) 
               .ToList();
from a in keys
group a by a.key into g
select new { a.Key, Count = g.Count() };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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