Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an IEnumerable<type> by three fields

I have defined a type as follows:

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

I have an IEnumerable<myType>.

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

The objects should be in order by last name. Where the last names are the same, they should be in order by first name. Where the first names are the same, they should be in order by middle name.

How do I do this?

like image 257
Vivian River Avatar asked Dec 13 '10 19:12

Vivian River


People also ask

How does OrderBy work in C#?

In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element.


1 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;
like image 157
Marc Gravell Avatar answered Sep 16 '22 15:09

Marc Gravell