Using the OrderBy and OrderByDescending in LINQ

By FoxLearn 2/22/2025 4:42:27 AM   2
The OrderBy and OrderByDescending operators in LINQ are powerful tools for sorting collections of data elements based on specific criteria. These operators enable efficient and flexible sorting of data, making it easier to organize and display information.

OrderBy Operator

The OrderBy operator sorts elements of a collection in ascending order based on one or more specified criteria. It returns a new collection containing the sorted elements.

Basic Syntax:

var orderedCollection = collection.OrderBy(item => item.Property);

Where:

  • collection is the data source you want to sort.
  • item => item.Property is a lambda expression that defines the sorting criteria in ascending order.

OrderByDescending Operator

The OrderByDescending operator is similar to OrderBy, but it sorts elements in descending order based on the specified criteria.

Basic Syntax:

var orderedCollection = collection.OrderByDescending(item => item.Property);

Where:

  • collection is the source data you want to sort.
  • item => item.Property is the lambda expression for sorting in descending order.

Suppose you have a collection of book objects, and you need to display the books in ascending order based on their title.

OrderBy Scenario: Sorting a List of Books by Title

List<Book> books = new List<Book>
{
    new Book { Title = "1984", Author = "George Orwell", PublicationYear = 1949 },
    new Book { Title = "To Kill a Mockingbird", Author = "Harper Lee", PublicationYear = 1960 },
    new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald", PublicationYear = 1925 }
};

var sortedBooks = books.OrderBy(book => book.Title);

foreach (var book in sortedBooks)
{
    Console.WriteLine($"{book.Title} by {book.Author} ({book.PublicationYear})");
}

OrderByDescending Scenario: Sorting a List of Movies by Rating

In another example, you have a list of movie objects with their ratings, and you want to display the movies in descending order of their ratings.

List<Movie> movies = new List<Movie>
{
    new Movie { Title = "Inception", Rating = 8.8 },
    new Movie { Title = "The Dark Knight", Rating = 9.0 },
    new Movie { Title = "Interstellar", Rating = 8.6 }
};

var topRatedMovies = movies.OrderByDescending(movie => movie.Rating);

foreach (var movie in topRatedMovies)
{
    Console.WriteLine($"{movie.Title}, Rating: {movie.Rating}");
}

Below is a C# example demonstrating the use of OrderBy and OrderByDescending to sort a list of books in a library system.

using System;
using System.Linq;

class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int PublicationYear { get; set; }
}

class Library
{
    static void Main()
    {
        Book[] books = new Book[]
        {
            new Book { Title = "The Great Gatsby", Author = "F. Scott Fitzgerald", PublicationYear = 1925 },
            new Book { Title = "1984", Author = "George Orwell", PublicationYear = 1949 },
            new Book { Title = "To Kill a Mockingbird", Author = "Harper Lee", PublicationYear = 1960 },
            new Book { Title = "Moby Dick", Author = "Herman Melville", PublicationYear = 1851 },
            new Book { Title = "Pride and Prejudice", Author = "Jane Austen", PublicationYear = 1813 }
        };

        // OrderBy: Sorting books by title in ascending order
        var sortedByTitle = books.OrderBy(book => book.Title);

        // OrderByDescending: Sorting books by author in descending order
        var sortedByAuthorDescending = books.OrderByDescending(book => book.Author);

        // OrderBy: Sorting books by publication year in ascending order
        var sortedByPublicationYear = books.OrderBy(book => book.PublicationYear);

        // Displaying sorted books by title
        Console.WriteLine("Books Sorted by Title:");
        foreach (var book in sortedByTitle)
        {
            Console.WriteLine($"{book.Title} by {book.Author} ({book.PublicationYear})");
        }

        // Displaying sorted books by author in descending order
        Console.WriteLine("\nBooks Sorted by Author (Descending):");
        foreach (var book in sortedByAuthorDescending)
        {
            Console.WriteLine($"{book.Title} by {book.Author} ({book.PublicationYear})");
        }

        // Displaying sorted books by publication year
        Console.WriteLine("\nBooks Sorted by Publication Year:");
        foreach (var book in sortedByPublicationYear)
        {
            Console.WriteLine($"{book.Title} by {book.Author} ({book.PublicationYear})");
        }
    }
}

Output:

Books Sorted by Title:
1984 by George Orwell (1949)
Moby Dick by Herman Melville (1851)
Pride and Prejudice by Jane Austen (1813)
The Great Gatsby by F. Scott Fitzgerald (1925)
To Kill a Mockingbird by Harper Lee (1960)

Books Sorted by Author (Descending):
To Kill a Mockingbird by Harper Lee (1960)
The Great Gatsby by F. Scott Fitzgerald (1925)
Pride and Prejudice by Jane Austen (1813)
Moby Dick by Herman Melville (1851)
1984 by George Orwell (1949)

Books Sorted by Publication Year:
Pride and Prejudice by Jane Austen (1813)
Moby Dick by Herman Melville (1851)
The Great Gatsby by F. Scott Fitzgerald (1925)
1984 by George Orwell (1949)
To Kill a Mockingbird by Harper Lee (1960)

Sorting a List of Products in a Store Survey

Consider a scenario where you're collecting survey responses about products in a store. Each product has a rating, and you want to sort them based on these ratings.

using System;
using System.Collections.Generic;
using System.Linq;

public class Product
{
    public string Name { get; set; }
    public double Rating { get; set; }
}

class StoreSurvey
{
    static void Main()
    {
        List<Product> products = new List<Product>
        {
            new Product { Name = "Laptop", Rating = 4.5 },
            new Product { Name = "Smartphone", Rating = 4.7 },
            new Product { Name = "Tablet", Rating = 4.2 },
            new Product { Name = "Headphones", Rating = 4.9 },
            new Product { Name = "Smartwatch", Rating = 4.1 }
        };

        // OrderBy: Sorting products by rating in ascending order
        var sortedByRatingAscending = products.OrderBy(product => product.Rating);

        // OrderByDescending: Sorting products by rating in descending order
        var sortedByRatingDescending = products.OrderByDescending(product => product.Rating);

        // Displaying products sorted by rating in ascending order
        Console.WriteLine("Products Sorted by Rating (Ascending):");
        foreach (var product in sortedByRatingAscending)
        {
            Console.WriteLine($"{product.Name} - Rating: {product.Rating}");
        }

        // Displaying products sorted by rating in descending order
        Console.WriteLine("\nProducts Sorted by Rating (Descending):");
        foreach (var product in sortedByRatingDescending)
        {
            Console.WriteLine($"{product.Name} - Rating: {product.Rating}");
        }
    }
}

Output:

Products Sorted by Rating (Ascending):
Smartwatch - Rating: 4.1
Tablet - Rating: 4.2
Laptop - Rating: 4.5
Smartphone - Rating: 4.7
Headphones - Rating: 4.9

Products Sorted by Rating (Descending):
Headphones - Rating: 4.9
Smartphone - Rating: 4.7
Laptop - Rating: 4.5
Tablet - Rating: 4.2
Smartwatch - Rating: 4.1

Benefits of Using OrderBy and OrderByDescending

  • Simplicity and Readability: These operators make sorting collections intuitive and concise. The syntax is clean and resembles natural language, making your code easier to read and maintain.

  • Flexibility: They can be used with any type of collection, including arrays, lists, and dictionaries. You can easily adjust the sorting criteria to suit your needs.

  • Efficiency: LINQ operations like OrderBy and OrderByDescending are optimized for performance, allowing developers to sort collections without writing manual sorting logic.

The OrderBy and OrderByDescending operators are powerful tools in LINQ for sorting data in a simple and effective way. Whether you need to sort items by title, rating, or any other property, these operators streamline the process.