如何对Generic List Asc或Desc进行排序?

Bar*_*Alp 21 .net c# asp.net sorting generics

我有一个类型为MyImageClass的泛型集合,而MyImageClass有一个布尔属性"IsProfile".我想对这个通用列表进行排序,其中IsProfile == true代表列表的开头.

我试过这个.

rptBigImages.DataSource = estate.Images.OrderBy(est=>est.IsProfile).ToList();
Run Code Online (Sandbox Code Playgroud)

使用图像上方的代码,最后一个IsProfile属性为true.但我希望它成为第一个指数.我需要一些Asc或Desc.然后我做了这个.

rptBigImages.DataSource = estate.Images.OrderBy(est=>est.IsProfile).Reverse.ToList();
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Ray*_*sen 39

怎么样:

estate.Images.OrderByDescending(est => est.IsProfile).ToList()
Run Code Online (Sandbox Code Playgroud)

这将通过IsProfile属性按降序对图像进行排序,然后从结果中创建新的List.


Mar*_*ell 33

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

如果您有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)));
}
Run Code Online (Sandbox Code Playgroud)

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