User987 User987 - 1 month ago 5
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)
.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 ???

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. I clearly have to store them into some kind of list or something...

Answer

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
               .ToList();

Update

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) 
               .ToList();