Using the OrderBy and OrderByDescending Operator in LINQ

The OrderBy and OrderByDescending operators are Operators in LINQ for sorting collections of data elements based on specified criteria. They provide a flexible and efficient way to impose a specific order on your data for various processing and presentation needs.

OrderBy Operator

The OrderBy operator is used to sort the elements of a collection in ascending order based on one or more specified criteria. It returns a new collection with the sorted elements.

Basic Syntax

var orderedCollection = collection.OrderBy(item => item.Property);
  • Collection: The source collection you want to sort.
  • item => item.Property: A lambda expression that specifies the property or criteria by which you want to sort the collection in ascending order.

How does OrderBy Operator work?

A simple breakdown of how OrderBy Operator works.

  1. Input: You start with a collection of elements (e.g., a list, array, or LINQ query result) that you want to sort.
  2. Sorting Criteria: You provide a lambda expression that defines the sorting criteria. This expression specifies the property or value based on which you want to sort the elements in ascending order.
  3. Sorting Process: The OrderBy operator processes the collection and performs a stable sort algorithm, arranging the elements in ascending order based on the specified criteria.
  4. Output: The operator returns a new collection (LINQ queryable) containing the sorted elements.
  5. Deferred Execution: The sorting operation is not immediately executed. Instead, it's deferred until you access or iterate over the sorted collection.

OrderByDescending Operator

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

Basic Syntax

var orderedCollection = collection.OrderByDescending(item => item.Property);
  • Collection: The source collection you want to sort.
  • item => item.Property: A lambda expression that specifies the property or criteria by which you want to sort the collection in descending order.

How does OrderByDescending Operator work?

A simple breakdown of how OrderByDescending Operator works.

  1. Input: Like with OrderBy, you start with a collection of elements.
  2. Sorting Criteria: You provide a lambda expression that defines the sorting criteria for descending order.
  3. Sorting Process: The OrderByDescending operator processes the collection and performs a stable sort algorithm, arranging the elements in descending order based on the specified criteria.
  4. Output: Similar to OrderBy, the operator returns a new collection containing the sorted elements.
  5. Deferred Execution: Just like OrderBy, the sorting operation is deferred until you actually use the sorted collection.

Real Scenario of OrderBy and OrderByDescending

  1. OrderBy Scenario: Sorting a List of Students by Their Grades
    Suppose you have a list of student objects, each containing their name and grade, and you want to sort the students in ascending order based on their grades.
  2. OrderByDescending Scenario: Sorting Employees by Salary
    Suppose you have a list of employee objects, each with properties like name and salary, and you want to sort them in descending order based on their salary.

This C# console application demonstrates a mini project for a Bollywood movie application. It simulates a simple movie browsing and watchlist management system using LINQ queries. Users can view recent and top-rated movies, as well as add movies to their watchlist. We have used OrderBy and OrderByDescending to sort the data.

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

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int Year { get; set; }
    public double Rating { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public List<Movie> Watchlist { get; set; } = new List<Movie>();
}

class Program
{
    static void Main(string[] args)
    {
        List<Movie> movies = new List<Movie>
        {
            new Movie { Id = 1, Title = "Dilwale Dulhania Le Jayenge", Year = 1995, Rating = 8.2 },
            new Movie { Id = 2, Title = "3 Idiots", Year = 2009, Rating = 8.4 },
            new Movie { Id = 3, Title = "Lagaan", Year = 2001, Rating = 8.1 },
            new Movie { Id = 4, Title = "Sholay", Year = 1975, Rating = 8.2 },
            new Movie { Id = 5, Title = "Mughal-E-Azam", Year = 1960, Rating = 8.4 },
            new Movie { Id = 6, Title = "Kabhi Khushi Kabhie Gham", Year = 2001, Rating = 7.4 },
            new Movie { Id = 7, Title = "Gangs of Wasseypur", Year = 2012, Rating = 8.2 },
            new Movie { Id = 8, Title = "Dangal", Year = 2016, Rating = 8.4 },
            new Movie { Id = 9, Title = "Rang De Basanti", Year = 2006, Rating = 8.1 },
            new Movie { Id = 10, Title = "PK", Year = 2014, Rating = 8.2 }
        };

        List<User> users = new List<User>
        {
            new User { Id = 1, Username = "Raj" },
            new User { Id = 2, Username = "Rahul" }
            
        };

        // Add a movie to user's watchlist
        User user = users.FirstOrDefault(u => u.Username == "Raj");
        Movie movieToAdd = movies.FirstOrDefault(m => m.Title == "Dangal");
        if (user != null && movieToAdd != null)
        {
            user.Watchlist.Add(movieToAdd);
        }

        // OrderBy
        var recentMovies = movies.Where(movie => movie.Year > 2010).OrderBy(movie => movie.Title);
        //OrderByDescending
        var topRatedMovies = movies.OrderByDescending(movie => movie.Rating).Take(2);

        // Display results
        Console.WriteLine("Recent Movies:");
        foreach (var movie in recentMovies)
        {
            Console.WriteLine($"{movie.Title} ({movie.Year}), Rating: {movie.Rating}");
        }

        Console.WriteLine("\nTop Rated Movies:");
        foreach (var movie in topRatedMovies)
        {
            Console.WriteLine($"{movie.Title} ({movie.Year}), Rating: {movie.Rating}");
        }

        // Display user's watchlist
        Console.WriteLine($"\n{user.Username}'s Watchlist:");
        foreach (var movie in user.Watchlist)
        {
            Console.WriteLine($"{movie.Title} ({movie.Year}), Rating: {movie.Rating}");
        }
    }
}

Output

Output

This C# console application demonstrates a mini project for a Product Survey application. .We have used OrderBy and OrderByDescending to sort the data with Dictionary Collection.

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

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

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public Dictionary<int, Product> ProductResponses { get; set; } = new Dictionary<int, Product>();
}

class ProductSurveyManagement
{
    static void Main(string[] args)
    {
        Dictionary<int, Product> products = new Dictionary<int, Product>
        {
            { 1, new Product { Id = 1, Name = "Mobile Phone", Rating = 4.5 } },
            { 2, new Product { Id = 2, Name = "Laptop", Rating = 4.0 } },
            { 3, new Product { Id = 3, Name = "Smart TV", Rating = 4.2 } },
            { 4, new Product { Id = 4, Name = "Headphones", Rating = 4.8 } },
            { 5, new Product { Id = 5, Name = "Camera", Rating = 4.6 } }
        };

        Dictionary<int, User> users = new Dictionary<int, User>
        {
            { 1, new User { Id = 1, Username = "Raj" } },
            { 2, new User { Id = 2, Username = "Suhani" } }
        };

        // Add a product response to user's dictionary
        User user = users.Values.FirstOrDefault(u => u.Username == "Raj");
        Product productResponse = products.Values.FirstOrDefault(p => p.Name == "Laptop");
        if (user != null && productResponse != null)
        {
            user.ProductResponses.Add(productResponse.Id, productResponse);
        }

        // OrderBy
        var highRatedProducts = products.Values.Where(product => product.Rating >= 4.5).OrderBy(product => product.Rating);
        // OrderByDescending
        var lowRatedProducts = products.Values.Where(product => product.Rating < 4.5).OrderByDescending(product => product.Rating);

        // Display high-rated products
        Console.WriteLine("High-Rated Products:");
        foreach (var product in highRatedProducts)
        {
            Console.WriteLine($"{product.Name}, Rating: {product.Rating}");
        }

        // Display low-rated products
        Console.WriteLine("\nLow-Rated Products:");
        foreach (var product in lowRatedProducts)
        {
            Console.WriteLine($"{product.Name}, Rating: {product.Rating}");
        }

        // Display user's product responses
        Console.WriteLine($"\n{user.Username}'s Product Responses:");
        foreach (var productEntry in user.ProductResponses)
        {
            Console.WriteLine($"{productEntry.Value.Name}, Rating: {productEntry.Value.Rating}");
        }
    }
}

Output

Output

The Program sorts and displays the books in ascending order by title, descending order by author, and ascending order by publication year.

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 = "Midnight's Children", Author = "Salman Rushdie", PublicationYear = 1981 },
            new Book { Title = "The God of Small Things", Author = "Arundhati Roy", PublicationYear = 1997 },
            new Book { Title = "A Suitable Boy", Author = "Vikram Seth", PublicationYear = 1993 },
            new Book { Title = "The White Tiger", Author = "Aravind Adiga", PublicationYear = 2008 },
            new Book { Title = "The Immortals of Meluha", Author = "Amish Tripathi", PublicationYear = 2010 },
            new Book { Title = "The Namesake", Author = "Jhumpa Lahiri", PublicationYear = 2003 },
            new Book { Title = "Interpreter of Maladies", Author = "Jhumpa Lahiri", PublicationYear = 1999 },
            new Book { Title = "Inheritance of Loss", Author = "Kiran Desai", PublicationYear = 2006 },
            new Book { Title = "Five Point Someone", Author = "Chetan Bhagat", PublicationYear = 2004 },
            new Book { Title = "The Rozabal Line", Author = "Ashwin Sanghi", PublicationYear = 2007 },
            new Book { Title = "The Palace of Illusions", Author = "Chitra Banerjee Divakaruni", PublicationYear = 2008 },
            new Book { Title = "Raavan: Enemy of Aryavarta", Author = "Amish Tripathi", PublicationYear = 2019 },
            new Book { Title = "Sacred Games", Author = "Vikram Chandra", PublicationYear = 2006 },
            new Book { Title = "The Alchemist of Loom", Author = "Elise Kova", PublicationYear = 2016 }
        };

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

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

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

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

        Console.WriteLine("\nSorted by Author (Descending):");
        foreach (var book in sortedByAuthorDescending)
        {
            Console.WriteLine($"Title: {book.Title}, Author: {book.Author}, Year: {book.PublicationYear}");
        }

        Console.WriteLine("\nSorted by Publication Year:");
        foreach (var book in sortedByPublicationYear)
        {
            Console.WriteLine($"Title: {book.Title}, Author: {book.Author}, Year: {book.PublicationYear}");
        }
    }
}

Output

Output

The `OrderBy` and `OrderByDescending` operators offer several advantages for sorting data within collections.  the key advantages of using these operators:

  1. Simplicity and Readability: The `OrderBy` and `OrderByDescending` operators provide a simple and intuitive way to sort data. The code reads like a natural language description of the sorting criteria, making it easy to understand and maintain.
  2. Flexibility: The operators can be used with a wide variety of data types and collections, including arrays, lists, dictionaries, and more. This flexibility makes it easy to sort different types of data without having to implement custom sorting logic each time.
  3. Consistency: The operators provide a consistent and standardized way to sort data, reducing the chances of inconsistencies or errors that might arise from manually implementing sorting logic.
  4. Support for Custom Comparers: You can provide custom comparison logic by using the `OrderBy` and `OrderByDescending` operators with a custom comparer. This allows you to sort data based on specific rules that are not covered by the default comparison.

Let's compare the OrderBy and OrderBydescending operators with a manual filtering approach using a for loop.

Example using OrderBy and OrderByDescending.

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

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 2, 8, 1, 9, 3, 7, 4, 6 };

        // Using OrderBy to sort in ascending order
        var sortedAscending = numbers.OrderBy(num => num);

        // Using OrderByDescending to sort in descending order
        var sortedDescending = numbers.OrderByDescending(num => num);

        Console.WriteLine("Sorted Ascending:");
        foreach (var num in sortedAscending)
        {
            Console.WriteLine(num);
        }

        Console.WriteLine("\nSorted Descending:");
        foreach (var num in sortedDescending)
        {
            Console.WriteLine(num);
        }
    }
}

Output

Output

For example, using a manual filtering approach with a for loop.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 2, 8, 1, 9, 3, 7, 4, 6 };

        // Manual sorting using a for loop (ascending)
        for (int i = 0; i < numbers.Count - 1; i++)
        {
            for (int j = i + 1; j < numbers.Count; j++)
            {
                if (numbers[i] > numbers[j])
                {
                    int temp = numbers[i];
                    numbers[i] = numbers[j];
                    numbers[j] = temp;
                }
            }
        }

        // Manual sorting using a for loop (descending)
        for (int i = 0; i < numbers.Count / 2; i++)
        {
            int temp = numbers[i];
            numbers[i] = numbers[numbers.Count - 1 - i];
            numbers[numbers.Count - 1 - i] = temp;
        }

        Console.WriteLine("Sorted Descending (Manual):");
        foreach (var num in numbers)
        {
            Console.WriteLine(num);
        }

        // Resetting the list to original order
        numbers.Reverse();

        Console.WriteLine("\nSorted Ascending (Manual):");
        foreach (var num in numbers)
        {
            Console.WriteLine(num);
        }
    }
}

Output

Output

In most scenarios, utilizing LINQs OrderBy and OrderByDescending operators are advisable due to their advantages in terms of code readability, performance, and development efficiency. However, for specialized cases requiring fine-tuned control over sorting logic, the manual for loop approach can be suitable. It's important to consider the trade-offs and choose the approach that best aligns with the specific requirements and goals of the sorting task.

If you encounter any issues or have further questions, feel free to let me know, and I'll be glad to assist!

Thank you for reading, and I hope this post has helped provide you with a better understanding of Using the `Where` Operator with List, Dictionary, Array, and ArrayList. 

"Keep coding, keep innovating, and keep pushing the boundaries of what's possible!

Happy Coding !


Similar Articles