IRONSOFTWAREHOME
.NET HELP

C# Orderby (How It Works For Developers)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: April 21, 2026

Sorting is a fundamental operation in any programming language, and the C# OrderBy method is a powerful tool for arranging elements within collections. Whether working with arrays, lists, or other enumerable structures, understanding how to leverage OrderBy can greatly enhance the readability and functionality of your code.

Later in this article, we will introduce IronPDF library from Iron Software and how we can use the LINQ OrderBy method and IronPDF to generate formatted and sorted PDFs.

What is the LINQ OrderBy Method?

The OrderBy method is part of the LINQ (Language-Integrated Query) library in C# and is specifically designed to sort elements in ascending order; as it is the default way to sort data, there is no need for an ascending keyword.

How to Use the LINQ OrderBy Method

Sorting Data in Ascending Order

In C#, there are two ways to apply this method: through method syntax or query syntax. We will use the method syntax as it is straightforward:

var sortedCollection = collection.OrderBy(item => item.OrderByProperty);

Here, the collection is the IEnumerable source collection you want to sort, and OrderByProperty is the property or expression by which you want to order the elements. The lambda expression within OrderBy specifies the sorting criterion.

Sorting Data in Descending Order

To sort in descending order, you can use the OrderByDescending method using the method-based syntax:

var sortedCollectionDesc = collection.OrderByDescending(item => item.OrderByProperty);

Sorting Data by Multiple Criteria

In real-world scenarios, you often need to sort a collection based on multiple criteria. OrderBy allows for this by chaining multiple ThenBy or ThenByDescending calls:

var multiSortedCollection = collection
    .OrderBy(item => item.OrderByProperty1)
    .ThenByDescending(item => item.OrderByProperty2);

In this example, the collection is first sorted by OrderByProperty1 in ascending order. Then, for elements with the same OrderByProperty1 value, it's sorted by OrderByProperty2 in descending order.

Custom Comparers

For more complex sorting requirements, you can use custom comparers. The OrderBy method allows you to pass an IComparer<T> implementation, as shown in the following example:

var customSortedCollection = collection.OrderBy(item => item.Property, new CustomComparer());

Here, CustomComparer is a class implementing the IComparer<T> interface, providing custom logic for comparing elements.

Practical Example: Sorting Objects

Sorting a List of Integers

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

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 5, 2, 8, 1, 7 };
        var sortedNumbers = numbers.OrderBy(num => num);
        Console.WriteLine("Sorted Numbers:");
        foreach (var number in sortedNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

In this example, a list of integers is sorted in ascending order using OrderBy.

Sorting a List of Strings

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

class Program
{
    static void Main()
    {
        List<string> names = new List<string> { "Alice", "Charlie", "Bob", "David" };
        var sortedNames = names.OrderBy(name => name);
        Console.WriteLine("Sorted Names:");
        foreach (var name in sortedNames)
        {
            Console.WriteLine(name);
        }
    }
}

This example demonstrates sorting a list of strings in ascending order alphabetically.

Sorting a List of Custom Objects

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

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe", Age = 30 },
            new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
            new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
        };
        var sortedPeople = people.OrderBy(person => person.Age);
        Console.WriteLine("Sorted People by Age:");
        foreach (var person in sortedPeople)
        {
            Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");
        }
    }
}

In this example, a list of custom Person objects is sorted based on the Age property in ascending order.

The following output is visible in the console:

C# Orderby (How It Works For Developers): Figure 1 - Output of the previous code sorting custom objects

Handling String Comparisons

When dealing with string properties, you might want to ensure case-insensitive sorting:

var sortedPeopleByName = people.OrderBy(person => person.LastName, StringComparer.OrdinalIgnoreCase);

This example uses the StringComparer.OrdinalIgnoreCase to perform a case-insensitive sort based on the LastName property.

Performance Considerations

While LINQ provides a concise way to sort collections, it's essential to consider performance implications, especially for large datasets. For performance-critical scenarios, you might explore alternatives like sorting in-place using the List<T>.Sort method.

Introducing IronPDF

Discover IronPDF capabilities within the C# PDF library from Iron Software, which helps to read and generate PDF docs. It can convert formatted documents with style information easily to PDF. IronPDF can generate PDFs from HTML strings, or it can download the HTML from the URL and then generate PDFs.

IronPDF shines when it comes to converting HTML to PDF, preserving all layouts and styles. It can generate PDFs from various web content, such as reports, invoices, and documentation. The tool works with HTML files, URLs, and HTML strings to create PDF files.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}

Installation

IronPDF can be installed using the NuGet package manager console or using the Visual Studio package manager.

PM > Install-Package IronPdf

You can also install IronPDF using NuGet Package Manager by searching "IronPDF" in the search bar.

C# Orderby (How It Works For Developers): Figure 2 - Installing IronPDF through the NuGet Package Manager

Generating a PDF Using IronPDF

Below is the code to generate a PDF report using an HTML string and IronPDF generator:

// See https://aka.ms/new-console-template for more information

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

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        List<Person> people = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe", Age = 30 },
            new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
            new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
        };
        
        // Sort people by age
        var sortedPeople = people.OrderBy(person => person.Age);
        
        string name = "Sam";
        var count = people.Count;
        
        // Generate an HTML string
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" + string.Join("\n", sortedPeople.Select(person => $"{person.FirstName} {person.LastName}, Age: {person.Age}"))
+ @"
</body>
</html>";

        // Create a new PDF document and save it
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
    }
}

Here we are first generating an HTML string from sortedPeople which is sorted in ascending order with all the formatting required for the reports. Then we use IronPDF to generate a PDF document. We use the RenderHtmlAsPdf method to convert the HTML string to a PDF document.

Output

The following output is available in the PDF:

C# Orderby (How It Works For Developers): Figure 3 - Output PDF from the previous code

Licensing (Free Trial Available)

A trial key can be obtained from IronPDF Trial License. This key needs to be placed in appsettings.json.

"IronPdf.LicenseKey": "your license key"
JSON

Provide your email to get a trial license.

Conclusion

The OrderBy method in C# is a versatile tool for sorting collections based on various criteria. Whether you're sorting in ascending or descending order, by single or multiple criteria, or using custom comparers, mastering OrderBy can significantly improve the clarity and efficiency of your code.

Together with IronPDF library for generating PDF documents, it is a great combination for generating a beautifully formatted and sorted collection as a document.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

No limitations. 100% unlocked. No credit card.

bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required