C # - Get the most commonly used string in the model list

I want to get the most common string from a list of models using Linq, but I really don't know how to do this.

Here is a sample code:

public ModelClass { public string name { get; set; } public int num { get; set; } } 

Imagine a huge list of ModelClass stored in a database

 // in some controller var model = from s in _db.SomeClass select s; string mostCommonName = ??????? 

How can I find the most common name from this list using linq?

+6
source share
2 answers

You can use GroupBy() to find rows with the same value.

 var mostCommonName = _db.SomeClass .GroupBy(x => x.Name) .Select(x => new { Name = x.Key, Count = x.Count() }) .OrderByDescending(x => x.Count) .Select(x => x.Name) .First(); 
+10
source
  var query = from n in _db.SomeClass group n by n.name into grouped select new { name = grouped.First().name, count = grouped.Count(), } into result orderby result.count descending select result; string mostCommonName = query.First().name; 
+1
source

All Articles