User987 User987 - 1 year ago 61
ASP.NET (C#) Question

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)

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 ???


Let's say I have count values that look like this:


I cannot simply Add 1 of this value into a variable called "Count" as @octavioccl suggested. I clearly have to store them into some kind of list or something...

Answer Source

Using the Select and projecting in an anonymous type:

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


You can also project your query using a 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) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download