[英]How to sort Generic List Asc or Desc?
I have a generic collection of type MyImageClass, and MyImageClass has an boolean property "IsProfile". 我有一个类型为MyImageClass的泛型集合,而MyImageClass有一个布尔属性“IsProfile”。 I want to sort this generic list which IsProfile == true stands at the start of the list.
我想对这个通用列表进行排序,其中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. 使用图像上方的代码,最后一个IsProfile属性为true。 But i want it to be at the first index.
但我希望它成为第一个指数。 I need something Asc or Desc .
我需要一些Asc或Desc 。 Then i did this.
然后我做了这个。
rptBigImages.DataSource = estate.Images.OrderBy(est=>est.IsProfile).Reverse.ToList();
Is there any easier way to do this ? 有没有更简单的方法来做到这一点?
Thanks 谢谢
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属性按降序对图像进行排序,然后从结果中创建新的List。
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 existing list, 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.Sort(x=>x.SomeProperty)
list.SortDescending(x=>x.SomeProperty)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.