C# 如何对通用列表 Asc 或 Desc 进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/532015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:03:06  来源:igfitidea点击:

How to sort Generic List Asc or Desc?

c#.netasp.netgenericssorting

提问by Barbaros Alp

I have a generic collection of type MyImageClass, and MyImageClass has an boolean property "IsProfile". I want to sort this generic list which IsProfile == true stands at the start of the list.

我有一个 MyImageClass 类型的泛型集合,MyImageClass 有一个布尔属性“IsProfile”。我想对 IsProfile == true 位于列表开头的通用列表进行排序。

I have tried this.

我试过这个。

rptBigImages.DataSource = estate.Images.OrderBy(est=>est.IsProfile).ToList();

with the code above the image stands at the last which IsProfile property is true. But i want it to be at the first index. I need something Asc or Desc. Then i did this.

使用上面的代码,图像位于 IsProfile 属性为真的最后一个位置。但我希望它位于第一个索引处。我需要一些Asc 或 Desc。然后我做了这个。

rptBigImages.DataSource = estate.Images.OrderBy(est=>est.IsProfile).Reverse.ToList();

Is there any easier way to do this ?

有没有更简单的方法来做到这一点?

Thanks

谢谢

采纳答案by Ray Booysen

How about:

怎么样:

estate.Images.OrderByDescending(est => est.IsProfile).ToList()

This will order the Images in descending order by the IsProfile Property and then create a new List from the result.

这将按 IsProfile 属性按降序对图像进行排序,然后根据结果创建一个新列表。

回答by Marc Gravell

You can use .OrderByDescending(...) - but note that with the LINQ methods you are creating a new ordered list, not ordering the existing list.

您可以使用 .OrderByDescending(...) - 但请注意,使用 LINQ 方法您正在创建一个新的有序列表,而不是对现有列表进行排序。

If you have a List<T>and want to re-order the existinglist, then you can use Sort()- and you can make it easier by adding a few extension methods:

如果您有一个List<T>并且想要重新排序现有列表,那么您可以使用Sort()- 并且您可以通过添加一些扩展方法使其更容易:

static void Sort<TSource, TValue>(this List<TSource> source,
        Func<TSource, TValue> selector) {
    var comparer = Comparer<TValue>.Default;
    source.Sort((x,y)=>comparer.Compare(selector(x),selector(y)));
}
static void SortDescending<TSource, TValue>(this List<TSource> source,
        Func<TSource, TValue> selector) {
    var comparer = Comparer<TValue>.Default;
    source.Sort((x,y)=>comparer.Compare(selector(y),selector(x)));
}

Then you can use list.Sort(x=>x.SomeProperty)and list.SortDescending(x=>x.SomeProperty).

然后你可以使用list.Sort(x=>x.SomeProperty)list.SortDescending(x=>x.SomeProperty)