Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: Order By Count of most common value

Tags:

c#

lambda

linq

I'm trying to create an "ordered" List of objects in c#, where the list will be ordered by the most common occurrences of values in ImdbId property. I am not using database i am getting the results from remote api in list and i need just to sort the list in elegant way.

class Movie
{
String ImdbId {get; set; }
String Name {get;set;}
    ... more properties
}

Example of unsorted list:

imdbId  | Name
698649  | "Sex and the City" Models and Mortals
698669  | "Sex and the City" The Awful Truth
698649  | "Sex and the City" Models and Mortals
698649  | "Sex and the City" Models and Mortals
698679  | "Sex and the City" The Drought
698697  | "Sex and the City" Valley of the Twenty-Something Guys
1568911 | War Horse

And the sorted should look like this:

imdbId  | Name
698649  | "Sex and the City" Models and Mortals
698649  | "Sex and the City" Models and Mortals
698649  | "Sex and the City" Models and Mortals
698669  | "Sex and the City" The Awful Truth
698679  | "Sex and the City" The Drought
698697  | "Sex and the City" Valley of the Twenty-Something Guys
1568911 | War Horse

Here is another example:

imdbId   |  Name
1568911 |   War Horse 
698690  |   "Sex and the City" The Turtle and the Hare 
698653  |   "Sex and the City" Old Dogs, New Dicks 
698690  |   "Sex and the City" The Turtle and the Hare 
698690  |   "Sex and the City" The Turtle and the aHare 
1000774 |       Sex and the City 

And the sorted should look like this:

imdbId  | Name
698690  | "Sex and the City" The Turtle and the Hare 
698690  | "Sex and the City" The Turtle and the Hare 
698690  | "Sex and the City" The Turtle and the aHare 
698653  | "Sex and the City" Old Dogs, New Dicks 
1000774 | Sex and the City
1568911 | War Horse  

I was trying following but no luck.

List<Movie> newList = List
     .OrderByDescending(a =>  a.ImdbId)
     .ThenByDescending(a => a.ImdbId.Count())
     .ToList();

Any idea how to achieve this with lambda or LINQ ?

like image 502
user2269223 Avatar asked Nov 18 '13 11:11

user2269223


1 Answers

Try this:

var newList = List.GroupBy(x=>x.ImdbId)
                  .OrderByDescending(g=>g.Count())
                  .SelectMany(g=>g).ToList();
like image 197
King King Avatar answered Nov 03 '22 02:11

King King