Overview

Represents an enumerable collection that has been ordered using a specified comparer. This class is used internally by LINQ to Objects to handle the results of ordering operations like OrderBy and ThenBy.

The OrderedEnumerable<T> class implements the IOrderedEnumerable<TElement> interface, which signifies that the sequence is ordered. It maintains the ordering information and applies it when enumerating the collection.

Syntax

C#
public sealed class OrderedEnumerable<TSource> : IEnumerable<TSource>, IOrderedEnumerable<TSource>

Type Parameters

  • TSource

    The type of the elements in the sequence.

Constructors

The OrderedEnumerable<T> class is an internal implementation detail and does not expose public constructors for direct instantiation.

Methods

  • GetEnumerator IEnumerator<TSource> IEnumerable<TSource>.GetEnumerator()

    Returns an enumerator that iterates through the ordered collection.

  • GetEnumerator IEnumerator IEnumerable.GetEnumerator()

    Returns an enumerator that iterates through the ordered collection.

  • CreateOrderedEnumerable IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer, bool descending)

    Internal helper method to create a new ordered enumerable, chaining ordering operations.

Inheritance Hierarchy

System.Object
  System.Linq.OrderedEnumerable<TSource>
                    

Remarks

Developers typically do not interact with the OrderedEnumerable<T> class directly. Instead, they use the extension methods provided by the Enumerable class, such as OrderBy, OrderByDescending, ThenBy, and ThenByDescending. These methods internally construct and return instances of OrderedEnumerable<T> to represent the ordered results.

The underlying data structure might be an array or another collection that has been sorted based on the specified key selector and comparer.

Example

The following example demonstrates how OrderBy internally utilizes the concept of ordered enumerables:

var numbers = new[] { 5, 1, 4, 2, 3 };

// OrderBy internally returns an OrderedEnumerable
var orderedNumbers = numbers.OrderBy(n => n);

foreach (var number in orderedNumbers)
{
    Console.WriteLine(number);
}
// Output: 1, 2, 3, 4, 5

// The order is preserved when further ordering is applied
var thenByOrdered = orderedNumbers.ThenBy(n => -n); // Example of chaining
foreach (var number in thenByOrdered)
{
    Console.WriteLine(number);
}
// Output: 1, 2, 3, 4, 5 (in this simple case, ThenBy doesn't change the order)