Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Comparer to sort IEnumerable in C# by different fields

Tags:

c#

linq

icomparer

I have a list of an object which need to be sorted depending on three different properties of the object. Example

CLass Object1{ Property1 , Property2, Property3}

ListObj = IEnumerable<Object1>

Foreach ( item in ListObj){

    if (item.Property1 == true)
       item goes at top of list
    if(item.Property2 == true)
       item goes end of list
    if(item.Property3 == true)
        item can go anywhere.
}

End list should be objects with Property1 = true followed by objects with Property2 = true followed by objects with Property3 = true

like image 762
user99322 Avatar asked Feb 26 '10 21:02

user99322


1 Answers

Why not use LINQ?

var orderedList = 
   ListObj.OrderByDescending(x => x.Property1)
          .ThenByDescending(x => x.Property2);
like image 173
David Morton Avatar answered Sep 24 '22 02:09

David Morton