using Comparer to sort IEnumerable in C# by different fields

user99322 picture user99322 · Feb 26, 2010 · Viewed 7.3k times · Source

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

Answer

David Morton picture David Morton · Feb 26, 2010

Why not use LINQ?

var orderedList = 
   ListObj.OrderByDescending(x => x.Property1)
          .ThenByDescending(x => x.Property2);