LINQ: 按最常见值的数量排序

7

我正在尝试在c#中创建一个“有序”的对象列表,其中该列表将按照ImdbId属性中值的最常出现次数进行排序。 我没有使用数据库,而是从远程API获取结果并需要以优雅的方式对列表进行排序。

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

无序列表示例:

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

而且排序后应该是这样的:
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

这里是另一个例子:
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 

而排序后应该像这样:
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  

我尝试了以下内容,但没有成功。
List<Movie> newList = List
     .OrderByDescending(a =>  a.ImdbId)
     .ThenByDescending(a => a.ImdbId.Count())
     .ToList();

有没有想过用Lambda或LINQ实现这个功能?

你写的语句有什么问题? - Imran Rizvi
你能给我一个例子吗? - user2269223
我的语句只是按照imdbid排序结果,而不是按照imdbid的最常见出现顺序排序。 - user2269223
你想把IMDb ID相同的电影放在一起保存吗? - tariq
@tariq 是的,我想保留所有结果,我只想按照imdbid最常见的出现顺序对列表进行排序。 - user2269223
显示剩余2条评论
1个回答

13

试试这个:

var newList = List.GroupBy(x=>x.ImdbId)
                  .OrderByDescending(g=>g.Count())
                  .SelectMany(g=>g).ToList();

@user2269223 不用谢,我理解你的感受 :) - King King

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接