views:

3448

answers:

2

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

+8  A: 

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.

Ray Booysen
=> instead of ->
Anton Gogolev
Fixed that for Ray.
Jon Skeet
Thanks for the answer and sorry for my unnecessary, i dont know why i didnt take attention the word under OrderBy on the intellisense.Thanks again
Barbaros Alp
Woops, thanks! :)
Ray Booysen
Is there any other way of just ordering the List instead of creating a new list except Marc's answer
Barbaros Alp
+11  A: 

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

Marc Gravell
Thanks Marc, so if i use Linq for ordering, does it mean that it causes a performance loss ?
Barbaros Alp
Well, in a very small way, but compared to data-binding you'll never notice it.
Marc Gravell
Thank you very much
Barbaros Alp
This is really helpful. Could this be extended to also do ThenOrderBy?
Ash Machine
@Ash, not "as is", since it is doing an immediate sort. It would need a bit more glue to do it - more than I can write at this moment...
Marc Gravell