c# - LINQ:按最常见值的计数排序

标签 c# linq lambda

我正在尝试在 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 实现这一点吗?

最佳答案

试试这个:

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

关于c# - LINQ:按最常见值的计数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20046563/

相关文章:

c# - 在 C# 中等效的 Javascript atob(string)

c# - WPF绑定(bind)不适用于ICommand

c# - LINQ .Any VS .Exists - 有什么区别?

c# - 公共(public)属性 List 需要 Concat 2 types with inheritance

c# - 接受 2 个 lambda 的方法有问题

c# - 从列表创建数据源

c# - 从 MS Access OLE 对象列创建图像文件(使用 C# 或 VB.NET)

c# - 如何使第二级包含对象

function - 为什么不能将变量移出闭包?

python - 如何使用 Lambda 应用 pd.crosstab