OrderBy and Grouping
Sort and group results.
Sorting with OrderBy
OrderBy sorts a sequence ascending by a key you select. The lambda returns the value to sort on.
It returns a new sorted sequence and is stable, meaning equal-key elements keep their original relative order.
using System;
using System.Linq;
int[] nums = { 4, 1, 3, 2 };
var sorted = nums.OrderBy(n => n);
Console.WriteLine(string.Join(", ", sorted));Descending Order
OrderByDescending sorts from largest to smallest by the selected key.
Use it directly rather than sorting ascending and reversing — it expresses intent clearly and sorts in one pass.
using System;
using System.Linq;
int[] scores = { 70, 95, 60, 88 };
var ranked = scores.OrderByDescending(s => s);
Console.WriteLine(string.Join(", ", ranked));All lessons in this course
- Where and Filtering
- Select and Projection
- OrderBy and Grouping
- Aggregates and ToList