LINQ:按计数排序是最常见的值 [英] LINQ: Order By Count of most common value
本文介绍了LINQ:按计数排序是最常见的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在c#中创建对象的有序"列表,其中该列表将按ImdbId属性中最常见的值出现顺序进行排序. 我没有使用数据库,而是从列表中的远程api获取结果,我只需要用一种优雅的方式对列表进行排序.
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
}
未排序列表的示例:
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
这里是另一个示例:
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();
有什么想法如何使用lambda或LINQ实现这一目标吗?
Any idea how to achieve this with lambda or LINQ ?
推荐答案
尝试一下:
var newList = List.GroupBy(x=>x.ImdbId)
.OrderByDescending(g=>g.Count())
.SelectMany(g=>g).ToList();
这篇关于LINQ:按计数排序是最常见的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文