Skip Navigation Links
Electric Harbour
Articles
Danish Alt Codes
Finnish Alt Codes
French Alt Codes
Norwegian Alt Codes
Spanish Alt Codes
Scandanavian Alt Codes
Swedish Alt Codes
Bulk Identity Insert
SQL Server Constraints
Visual Studio Shortcuts
LINQ Cast Operator
LINQ Group By Example
LINQ Not In Example
LINQ Order By Example
Tools
CSV String Generator
About
Curriculum Vitæ
Contact

LINQ Order By Examples in C#

The order by clause in LINQ is easy to learn due to its close resemblance to the T-SQL syntax. For example, let’s say we have a list of dogs and we want to sort the list by the name of the dog. Here is a LINQ query expression that does that:

var queryOrder = (from x in dogs
                  orderby x.Name
                  select x).ToList();

An even more concise way of writing this is using the lambda expression equivalent:

var lambdaOrder = dogs.OrderBy(x => x.Name);

These are easy and somewhat similair statments, but the syntax diverges when you want to order by multiple columns. Here is the query expression that sorts the dog list by breed then by name:

var queryOrder = (from x in dogs
                  orderby x.BreedName, x.Name
                  select x).ToList();

Again this is close to the T-SQL syntax. However, as usual, the lambda expression equivalent is less intuitive but more concise. To do this we use the OrderBy operator followed by the ThenBy operator:

var lambdaOrder = dogs.OrderBy(x => x.BreedName).ThenBy(x => x.Name);

Being able to perform sorts using such a small amount of code is one of my favorite features of LINQ. I don’t do it often, but now when I work on a system that doesn’t support LINQ it makes me groan.