# List OrderBy (in-memory)

> Sort a local List<T> in memory by a key selector, returning a NEW sorted List<T> (the source is untouched). Ascending or descending, stable, exactly like C#'s Enumerable.OrderBy; chain Take(n) for top-k. Distinct from an entity-query OrderBy, which lowers to SQL.

<!-- id: function-list-orderby · area: function · stability: stable · html: https://osysharp.com/reference/function/list-orderby/ -->

## Summary        {#summary}
`list.OrderBy(x => x.Key)` sorts a local `List<T>` by the selected key and returns a **new** sorted
`List<T>` — the source list is left unchanged, exactly like C#'s `Enumerable.OrderBy(...)`.
`OrderByDescending` sorts in reverse. The sort is **stable**: elements with equal keys keep their input
order.

## Signature      {#signature}
```osy syntax
list.OrderBy(<element> x => <key>)            // ascending  → a new List<T>
list.OrderByDescending(<element> x => <key>)  // descending → a new List<T>
```

## Description    {#description}
The receiver is a `List<T>` (`new List<T>()` or a `Text.Split` result). The key selector `x => x.Key`
projects each element to a **comparable** value (a number, string, date, …); a non-comparable key is a
compile error. The result is itself a `List<T>`, so it can be iterated, indexed
(`sorted[0]`, see [List indexer](https://osysharp.com/reference/function/list-indexer/)), counted, and sorted again.

This is an **in-memory** sort with no database dependency — the twin of an entity-query `OrderBy`, which
instead lowers to SQL `ORDER BY`. Use it to rank locally-built lists (merge results, computed scores).

Single-key only for now; `ThenBy` is not yet available.

Want the **source list itself** reordered rather than a copy? That is `list.Sort()` — see
[List Sort, Reverse and RemoveAt (in place)](https://osysharp.com/reference/function/list-sort/). The two agree about what the order is and differ only in whether your list moved.

`list.Take(n)` returns a **new** `List<T>` of the first `n` elements (in memory). `n` is any integer and is
**clamped** like C# — `n` larger than the list keeps all elements, `n <= 0` yields an empty list, and it
never throws. It chains after `OrderBy` for top-k ranking: `items.OrderByDescending(k).Take(3)`.

## Examples       {#examples}
```osy title="rank a local list" test app=list-orderby
class Scored { public string Id; public decimal Score; }

List<Scored> Top3(List<Scored> items) {
  return items.OrderByDescending(s => s.Score).Take(3);   // top 3 by score; input order kept on ties
}
```

## See also       {#see-also}
- [List Sort, Reverse and RemoveAt (in place)](https://osysharp.com/reference/function/list-sort/) — `Sort`/`Reverse`/`RemoveAt`, which change the list in place instead
- [List indexer](https://osysharp.com/reference/function/list-indexer/) — positional access on the sorted result
- [Text.Split](https://osysharp.com/reference/function/text-split/) — produces a `List<string>` you can sort
