System.Linq.IOrderedEnumerable<T> Interface

public interface IOrderedEnumerable<T> : IEnumerable<T>

Interface Members

Represents an enumerable collection of elements that has been ordered. This interface is implemented by the results of the OrderBy and ThenBy methods.

Implements

IEnumerable<T>

This interface inherits members from IEnumerable<T>.

Type Parameters

T: The type of the elements in the collection.

Properties

Name Description
OrderedEnumerable<T>.Provider Gets the IOrderedEnumerableProvider for this ordered enumerable.

Methods

This interface does not define any new members beyond those inherited from IEnumerable<T>.

Remarks

The IOrderedEnumerable<T> interface is an extension of the IEnumerable<T> interface. It is used to represent the result of LINQ query operations that involve sorting, such as OrderBy, OrderByDescending, ThenBy, and ThenByDescending.

When you apply an ordering operation to a sequence, the result implements IOrderedEnumerable<T>. This allows for subsequent ordering operations to be chained correctly. For example, you can call ThenBy on the result of an OrderBy operation.

Examples

// Simple example of using IOrderedEnumerable with OrderBy and ThenBy
using System;
using System.Collections.Generic;
using System.Linq;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; ; }
}

public class Example
{
    public static void Main(string[] args)
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30, City = "New York" },
            new Person { Name = "Bob", Age = 25, City = "Los Angeles" },
            new Person { Name = "Charlie", Age = 30, City = "New York" },
            new Person { Name = "David", Age = 25, City = "Chicago" }
        };

        // Order by Age, then by Name
        IOrderedEnumerable<Person> orderedPeople = people
            .OrderBy(p => p.Age)
            .ThenBy(p => p.Name);

        // The result 'orderedPeople' is of type IOrderedEnumerable<Person>

        foreach (var person in orderedPeople)
        {
            Console.WriteLine($"{person.Name} ({person.Age}) from {person.City}");
        }

        // Example of further ordering by City, demonstrating chaining
        IOrderedEnumerable<Person> furtherOrderedPeople = orderedPeople
            .ThenBy(p => p.City);

        Console.WriteLine("\nFurther ordered by City:");
        foreach (var person in furtherOrderedPeople)
        {
            Console.WriteLine($"{person.Name} ({person.Age}) from {person.City}");
        }
    }
}