> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# C# Orderby Clause

The `orderby` clause is a Language Integrated Query (LINQ) expression used to sort the elements of a sequence based on one or more key selectors. It dictates the iteration order of the returned `IEnumerable<T>` or `IQueryable<T>` by evaluating the specified keys, without mutating the underlying data source.

## Syntax

```csharp theme={"dark"}
from rangeVariable in dataSource
orderby keySelector1 [ascending | descending] [, keySelector2 [ascending | descending] ...]
select rangeVariable;
```

* **`keySelector`**: An expression that extracts the value used for sorting from the range variable. For LINQ to Objects (`IEnumerable<T>`), the return type typically implements `IComparable<T>` or `IComparable`, unless a custom `IComparer<T>` is injected via method syntax. For `IQueryable<T>`, the type must simply be translatable by the underlying query provider (e.g., to SQL).
* **`ascending` / `descending`**: Optional contextual keywords that dictate the sort direction. If omitted, the default is `ascending`.

## Compiler Translation and Method Syntax

At compile time, the C# compiler translates the `orderby` query syntax into standard query operator method calls.

* A single `orderby` key translates to `Enumerable.OrderBy` or `Enumerable.OrderByDescending` (or their `Queryable` equivalents).
* Subsequent comma-separated keys translate to `Enumerable.ThenBy` or `Enumerable.ThenByDescending`.

**Single Key Translation:**

```csharp theme={"dark"}
// Query Syntax
var query = from element in sequence
            orderby element.PrimarySortKey descending
            select element;

// Method Syntax Equivalent
var methodQuery = sequence.OrderByDescending(element => element.PrimarySortKey);
```

**Multiple Key Translation:**

```csharp theme={"dark"}
// Query Syntax
var query = from element in sequence
            orderby element.PrimarySortKey, element.SecondarySortKey descending
            select element;

// Method Syntax Equivalent
var methodQuery = sequence
    .OrderBy(element => element.PrimarySortKey)
    .ThenByDescending(element => element.SecondarySortKey);
```

## Technical Characteristics

**Deferred Execution**
The `orderby` clause utilizes deferred execution. The sorting algorithm is not executed when the query is defined. Instead, the sequence is evaluated and sorted only when the resulting `IEnumerable<T>` or `IQueryable<T>` is enumerated (e.g., via a `foreach` loop or by calling `.ToList()`).

**Stable Sorting**
For LINQ to Objects (`IEnumerable<T>`), the underlying `OrderBy` and `ThenBy` methods perform a *stable sort*. If two elements yield identical values for all specified key selectors, the sorting algorithm preserves the relative order of those elements as they appeared in the original, unsorted sequence. However, for `IQueryable<T>` implementations (such as Entity Framework or LINQ to SQL), stable sorting is generally *not* guaranteed. Relational databases do not guarantee a stable sort unless a unique key is explicitly included in the sort criteria.

**Type Comparison**
By default, in LINQ to Objects, the `orderby` clause relies on `Comparer<T>.Default` to compare the extracted keys. This comparer first checks if the key type implements the generic `IComparable<T>` interface. If it does not, it falls back to checking for the non-generic `IComparable` interface. If the type implements *neither* interface and no custom comparer is provided, an `ArgumentException` is thrown at runtime during enumeration. While method syntax allows passing a custom `IComparer<T>` directly into the `OrderBy` method (bypassing the interface requirement), the query syntax `orderby` clause does not support explicit comparer injection. For `IQueryable<T>`, comparison logic is dictated entirely by the translation engine and the target data store.

**Memory Allocation**
Because sorting requires evaluating the entire sequence to determine the correct order of the first yielded element, `orderby` forces the enumeration of the entire source sequence into memory (or into a temporary buffer) before yielding the first result. This makes it a stateful, blocking operation in LINQ to Objects.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor C# Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
