【问题标题】:LINQ: Order By Count of most common valueLINQ:按最常见值的计数排序
【发布时间】:2013-11-18 11:24:11
【问题描述】:

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

【问题讨论】:

  • 顺便说一句,你有没有尝试过?
  • 你写的陈述有什么问题?
  • 你能举个例子吗
  • 在我的声明中,它只是按 imdbid 排序结果,而不是按最常见的 imdbid 排序
  • @Ian Nelson 抱歉,我没有看到,我编辑了我的问题

标签: c# linq lambda


【解决方案1】:

试试这个:

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

【讨论】:

  • @user2269223 不客气,我理解你的感受:)
猜你喜欢
  • 2014-03-06
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 2016-07-17
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
相关资源
最近更新 更多