LINQ Interview Question #34

What does OrderBy do in LINQ?

Filtering, Projection, Ordering & Element Operators Junior Beginner

Quick Interview Answer

OrderBy sorts a sequence in ascending order according to a key selector. For strings this typically means ascending text order, and for numeric or date values it means lowest or earliest first according to the comparer.

Detailed Explanation

OrderBy sorts a sequence in ascending order according to a key selector. For strings this typically means ascending text order, and for numeric or date values it means lowest or earliest first according to the comparer.

OrderBy begins a new ordering definition. Additional ordering levels should normally use ThenBy or ThenByDescending.

Code Example

var byName = products
    .OrderBy(p => p.Name);

var byPrice = products
    .OrderBy(p => p.Price);