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 ?
Try this:
var newList = List.GroupBy(x=>x.ImdbId)
.OrderByDescending(g=>g.Count())
.SelectMany(g=>g).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With