LINQ Syntax: Sort C# List

LINQ SYNTAX: USE ORDERBY TO SORT A LIST

by

The Language Integrated Query (LINQ) is a syntax that allows developers to sort, filter, and perform other aggregate operations on collections in C#. This tutorial will introduce you to LINQ and teach you how to use the OrderBy method to sort your data.

Initial Setup

This tutorial will build off the previous tutorial, which introduced C# lists. In that example, we created a class for cataloging books in a library. Copy and paste the following code to get started. You will build of this template as the tutorial progresses. This code creates a Book class and initializes a new List of five Book elements. If you are unsure about a particular line or section, please review the previous tutorial for explanations.

using System;
using System.Collections.Generic;
 
namespace IntroducingLINQ
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Book> bookList = new List<Book>()
            {
                new Book("Les Miserables", "Victor Hugo", 1862),
                new Book("L'Etranger", "Albert Camus", 1942),
                new Book("Madame Bovary", "Gustave Flaubert", 1857),
                new Book("Le Comte de Monte-Cristo", "Alexandre Dumas", 1844),
                new Book("Candide", "Voltaire", 1759)
            };
 
            Console.ReadLine();
 
        }
    }
 
    class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public int PubDate { get; set; }
 
        public Book(string title, string author, int pubDate)
        {
            Title = title;
            Author = author;
            PubDate = pubDate;
        }
    }
}

LINQ Query Syntax

You have a collection of five books. Now, suppose you want to order the books by publication date. The best way to accomplish this is by using the Language Integrated Query featured of C# known as LINQ. There are two different styles of LINQ syntax. First, we will review the Query Syntax, which will look familiar if you have a background in SQL databases. To get started, add a reference to the LINQ namespace in your project.

using System.Linq;

Now, you can sort the list using the query syntax below.

var sortedBooks = from book in bookList
                  orderby book.PubDate ascending
                  select book;

On Line 20, you have declared a new variable called sortedBooks. This variable will contain the set or subset of the collection returned by the query. The query statement also begins on Line 20 and continues through Line 22.

Line 20 tells the program to go through the items in the collection bookList. Line 21 invokes the orderby keyword and identifies the property that you want to order the list by. In this example, you are sorting the books by publication date. You must also define whether you want to order the books in ascending or descending order. The ordered list is then saved as a new collection called sortedBooks.

You can loop through the elements in sortedBooks to verify that the sort operation has been completed.

foreach (Book book in sortedBooks)
{
    Console.WriteLine($"{book.PubDate}, {book.Title}");
}

LINQ Method Syntax

The second LINQ syntax is known as the Method Syntax. The method syntax is more common in C# applications. It is helpful to understand the logic from the query syntax example in order to master the method syntax. To get started with LINQ using the method syntax, don't forget to reference the LINQ namespace.

using System.Linq;

To learn how to sort a list using the method syntax, we will walk through the following example.

var sortedBooks = bookList.OrderBy(p => p.PubDate);

This line creates a new variable sortedBooks which will contain the ordered list of books. It then uses a lambda expression, which is signified by the lambda operator =>. The lambda operator is typically read as "goes to."

A lambda expression can be viewed as a miniature method. In this example, the expression p => p.PubDate is used with respect to the OrderBy method. It is used to express the following logic: For each item p in the collection, order by property (publication year, in this example).

LINQ's OrderBy method sorts by ascending order. To sort in descending order, you must specify the OrderByDescending method.

var sortedBooks = bookList.OrderByDescending(p => p.PubDate);

The method syntax is a concise way to query a collection in C#, and it is easy to use once you understand what a lambda expression is. Lambdas are powerful tools, and you will be exposed to them more in the next tutorial where you learn how to filter a C# list.

The Bottom Line

In this tutorial, you were introduced to C#'s Language Integrated Query feature. You learned two syntaxes for working with LINQ. The Query Syntax is familiar to SQL developers, but the Method Syntax is generally the preferred approach for C# developers. Finally, you learned how to sort a list collection using both approaches. If you have any questions about sorting a list in C#, or about either of the approaches for working with LINQ, sound off in the comments.


Don't stop learning!

There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.


Did you know?

Our beautiful, multi-column C# reference guides contain more than 150 tips and examples to make it even easier to write better code.

Get your cheat sheets