Linq OrderBy Any Property

I know how to order one property, then another property. I am wondering if there is a linq way to order by any property (or several properties at the same time).

For example, a list of names:

   ->Adam     Jones
   ->Dude     Lebowski
   ->Zander   Berry

Will be sorted:

   ->Adam     Jones
     Zander ->Berry
   ->Dude     Lebowski
+5
source share
2 answers

This is a strange desire.

You can pass any Func <TSource, TKey> you like in OrderBy: -

names.OrderBy(x => x.FirstName.CompareTo(x.LastName) < 0
                     ? x.FirstName
                     : x.LastName);

Or, if you think the built-in triple version looks ugly (or if you need to reuse sorting all over the place), you can write your own IComparer: -

http://msdn.microsoft.com/en-us/library/bb549422.aspx

class PersonFirstOrLastNameComparer : IComparer<Person>
{
  public int Compare( Person x, Person y )
  {
    return GetKey( x ).CompareTo( GetKey( y ) );
  }

  private String GetKey( Person person )
  {
    if ( person.FirstName.CompareTo( person.LastName ) < 0 )
    {
      return person.FirstName;
    }
    else
    {
      return person.LastName;
    }
  }
}

and: -

names.OrderBy(x => x, new PersonFirstOrLastNameComparer());

, . , , , .

, , ( , Person.SortKey, , CompareTo) . , , - . , ( ViewModel) .

+6

:

.OrderBy(obj => (obj.PropA < obj.PropB) ? obj.PropA : obj.PropB)
+3

All Articles