Sort IEnumerable <type> by Three Fields

I defined the type as follows:

public class myType
{
    public string firstName { get; set; }
    public string middleName { get; set; }
    public string lastName { get; set; }
}

I have one IEnumerable<myType>.

I want to use the extension .OrderBy()to sort my myType list as follows.

Objects must be in order by last name. If the names of the latter match, they must be in order by name. If the first names match, they should be in order by the middle name.

How to do it?

+5
source share
2 answers
var qry = items.OrderBy(x => x.lastName).ThenBy(x => x.firstName)
    .ThenBy(x => x.middleName);

or in LINQ syntax:

var qry = from x in items
          orderby x.lastName, x.firstName, x.middleName
          select x;
+17
source
myList.OrderBy(t => t.lastName).ThenBy(t => t.firstName).ThenBy(t => t.middleName)

In addition, each OrderByand ThenByhas the version Descending, why OrderByDescendingandThenByDescending

+7
source

All Articles