How to sort Generic List Asc or Desc?

Posted on

Problem :

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.

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.

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

Is there any easier way to do this ?

Thanks

Solution :

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.

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

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:

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).

Leave a Reply

Your email address will not be published. Required fields are marked *