Saltar al pie de página
.NET AYUDA

C# Orderby (Cómo Funciona para Desarrolladores)

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);
var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
Dim sortedCollection = collection.OrderBy(Function(item) item.OrderByProperty)
$vbLabelText   $csharpLabel

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);
var sortedCollectionDesc = collection.OrderByDescending(item => item.OrderByProperty);
Dim sortedCollectionDesc = collection.OrderByDescending(Function(item) item.OrderByProperty)
$vbLabelText   $csharpLabel

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);
var multiSortedCollection = collection
    .OrderBy(item => item.OrderByProperty1)
    .ThenByDescending(item => item.OrderByProperty2);
Dim multiSortedCollection = collection.OrderBy(Function(item) item.OrderByProperty1).ThenByDescending(Function(item) item.OrderByProperty2)
$vbLabelText   $csharpLabel

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());
var customSortedCollection = collection.OrderBy(item => item.Property, new CustomComparer());
Dim customSortedCollection = collection.OrderBy(Function(item) item.Property, New CustomComparer())
$vbLabelText   $csharpLabel

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);
        }
    }
}
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);
        }
    }
}
Imports System
Imports System.Linq
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		Dim numbers As New List(Of Integer) From {5, 2, 8, 1, 7}
		Dim sortedNumbers = numbers.OrderBy(Function(num) num)
		Console.WriteLine("Sorted Numbers:")
		For Each number In sortedNumbers
			Console.WriteLine(number)
		Next number
	End Sub
End Class
$vbLabelText   $csharpLabel

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);
        }
    }
}
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);
        }
    }
}
Imports System
Imports System.Linq
Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main()
		Dim names As New List(Of String) From {"Alice", "Charlie", "Bob", "David"}
		Dim sortedNames = names.OrderBy(Function(name) name)
		Console.WriteLine("Sorted Names:")
		For Each name In sortedNames
			Console.WriteLine(name)
		Next name
	End Sub
End Class
$vbLabelText   $csharpLabel

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}");
        }
    }
}
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}");
        }
    }
}
Imports System
Imports System.Linq
Imports System.Collections.Generic

Friend Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
	Public Property Age() As Integer
End Class

Friend Class Program
	Shared Sub Main()
		Dim people As New List(Of Person) From {
			New Person With {
				.FirstName = "John",
				.LastName = "Doe",
				.Age = 30
			},
			New Person With {
				.FirstName = "Alice",
				.LastName = "Smith",
				.Age = 25
			},
			New Person With {
				.FirstName = "Bob",
				.LastName = "Johnson",
				.Age = 35
			}
		}
		Dim sortedPeople = people.OrderBy(Function(person) person.Age)
		Console.WriteLine("Sorted People by Age:")
		For Each person In sortedPeople
			Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}")
		Next person
	End Sub
End Class
$vbLabelText   $csharpLabel

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);
var sortedPeopleByName = people.OrderBy(person => person.LastName, StringComparer.OrdinalIgnoreCase);
Dim sortedPeopleByName = people.OrderBy(Function(person) person.LastName, StringComparer.OrdinalIgnoreCase)
$vbLabelText   $csharpLabel

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");
    }
}
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");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

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

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

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Installation

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

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");
    }
}
// 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");
    }
}
' See https://aka.ms/new-console-template for more information

Imports Microsoft.VisualBasic
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Linq

Friend Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
	Public Property Age() As Integer
End Class

Friend Class Program
	Shared Sub Main()
		Dim people As New List(Of Person) From {
			New Person With {
				.FirstName = "John",
				.LastName = "Doe",
				.Age = 30
			},
			New Person With {
				.FirstName = "Alice",
				.LastName = "Smith",
				.Age = 25
			},
			New Person With {
				.FirstName = "Bob",
				.LastName = "Johnson",
				.Age = 35
			}
		}

		' Sort people by age
		Dim sortedPeople = people.OrderBy(Function(person) person.Age)

		Dim name As String = "Sam"
		Dim count = people.Count

		' Generate an HTML string
		Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" & String.Join(vbLf, sortedPeople.Select(Function(person) $"{person.FirstName} {person.LastName}, Age: {person.Age}")) & "
</body>
</html>"

		' Create a new PDF document and save it
		Dim pdfDocument = New ChromePdfRenderer()
		pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

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"

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.

Preguntas Frecuentes

¿Cómo funciona el método OrderBy de C#?

El método OrderBy de C#, parte de la biblioteca LINQ, ordena elementos de una colección en orden ascendente. Puede usarse tanto con la sintaxis de método como con la sintaxis de consulta, y es lo suficientemente versátil como para manejar enteros, cadenas y objetos personalizados.

¿Cómo puedo ordenar los datos en orden descendente usando C#?

Para ordenar datos en orden descendente en C#, puedes usar el método OrderByDescending. Esto es parte de la biblioteca LINQ y complementa a OrderBy para diferentes necesidades de clasificación.

¿Es posible ordenar por múltiples campos en C#?

Sí, en C#, puedes ordenar por múltiples campos usando OrderBy en combinación con ThenBy o ThenByDescending. Esto permite criterios de clasificación complejos, permitiendo a los desarrolladores ordenar colecciones basadas en múltiples atributos.

¿Qué es un comparador personalizado y cómo se utiliza en la clasificación de C#?

Un comparador personalizado en C# es una implementación de la interfaz IComparer, que proporciona lógica personalizada para comparar elementos durante la clasificación. Esto es útil para ordenar objetos complejos o cuando el comportamiento de clasificación predeterminado no cumple con requisitos específicos.

¿Cómo puedo usar IronPDF para generar PDFs en C#?

Puedes usar IronPDF en C# para generar PDFs a partir de cadenas HTML, archivos o incluso URLs web. IronPDF mantiene el diseño y estilo del contenido original, siendo ideal para crear documentos profesionales como informes y facturas.

¿Cuáles son los pasos para instalar IronPDF en un proyecto C#?

IronPDF se puede instalar en un proyecto C# usando el gestor de paquetes NuGet. Puedes ejecutar el comando dotnet add package IronPdf en la consola o usar el gestor de paquetes en Visual Studio para agregarlo a tu proyecto.

¿Cómo se integra IronPDF con C# OrderBy para la generación de PDFs?

IronPDF se puede integrar con C# OrderBy para crear informes en PDF ordenados y formateados. Al ordenar las colecciones de datos usando OrderBy antes de renderizar, aseguras que la salida en PDF esté organizada según tus criterios de ordenación.

¿Puede IronPDF convertir una URL de página web en un PDF?

Sí, IronPDF puede convertir contenido web desde una URL en un documento PDF. Preserva el diseño y los estilos originales de la página web, haciéndolo adecuado para archivar páginas web o crear versiones imprimibles.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más