0Pricing
C# Academy · Lesson

OrderBy and Grouping

Sort and group results.

OrderBy and Grouping is a free C# Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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));

Sorting by a Property

For objects, select the property to order by. OrderBy(p => p.Age) sorts people from youngest to oldest.

The key can be any comparable type — numbers, strings, dates — or anything implementing IComparable.

using System;
using System.Linq;
using System.Collections.Generic;

record P(string Name, int Age);
var people = new List<P> { new("Ana", 30), new("Bo", 22) };
var byAge = people.OrderBy(p => p.Age);
foreach (var p in byAge) Console.WriteLine(p.Name);

Secondary Sort with ThenBy

ThenBy adds a tie-breaker. After OrderBy, it sorts elements that share the primary key by a second key.

You can chain several ThenBy/ThenByDescending calls for multi-level ordering.

using System;
using System.Linq;
using System.Collections.Generic;

record P(string Name, int Age);
var people = new List<P> { new("Bo", 30), new("Ana", 30), new("Cy", 22) };
var ordered = people.OrderBy(p => p.Age).ThenBy(p => p.Name);
foreach (var p in ordered) Console.WriteLine($"{p.Age} {p.Name}");

Why Not a Second OrderBy

Calling OrderBy twice does not give a tie-breaker — the second call fully re-sorts and discards the first ordering.

For layered sorting always use ThenBy after the initial OrderBy.

using System;
using System.Linq;
using System.Collections.Generic;

record P(string N, int A);
var ps = new List<P> { new("Bo", 30), new("Ana", 30) };
var wrong = ps.OrderBy(p => p.A).OrderBy(p => p.N);
foreach (var p in wrong) Console.WriteLine(p.N);

Query Syntax orderby

Query syntax has an orderby clause. List multiple keys separated by commas, optionally with descending.

orderby p.Age, p.Name descending sorts by age, then by name in reverse for ties.

using System;
using System.Linq;
using System.Collections.Generic;

record P(string N, int A);
var ps = new List<P> { new("Bo", 30), new("Ana", 30), new("Cy", 22) };
var q = from p in ps orderby p.A, p.N select p.N;
Console.WriteLine(string.Join(", ", q));

Grouping with GroupBy

GroupBy partitions a sequence into groups sharing a key. It returns a sequence of IGrouping<TKey, TElement>.

Each grouping exposes its Key and is itself iterable over the elements in that group.

using System;
using System.Linq;

int[] nums = { 1, 2, 3, 4, 5, 6 };
var groups = nums.GroupBy(n => n % 2 == 0 ? "even" : "odd");
foreach (var g in groups)
  Console.WriteLine($"{g.Key}: {string.Join(\",\", g)}");

Group Key and Members

Each group's Key identifies the partition, and iterating the group yields its members. You can call Count() on a group directly.

This is how you build histograms, tallies, and category breakdowns.

using System;
using System.Linq;

string[] fruit = { "apple", "avocado", "banana", "cherry" };
var byLetter = fruit.GroupBy(f => f[0]);
foreach (var g in byLetter)
  Console.WriteLine($"{g.Key}: {g.Count()}");

Group Then Project

A common pattern projects each group into a summary object using Select after GroupBy.

You read the Key and aggregate the members — for example a count or a sum per group.

using System;
using System.Linq;
using System.Collections.Generic;

record Sale(string City, int Amt);
var sales = new List<Sale> { new("NY", 5), new("LA", 3), new("NY", 2) };
var totals = sales.GroupBy(s => s.City)
                  .Select(g => new { g.Key, Sum = g.Sum(x => x.Amt) });
foreach (var t in totals) Console.WriteLine($"{t.Key}={t.Sum}");

GroupBy with Element Selector

GroupBy has an overload taking a second lambda — an element selector — that projects what each group stores, not just how it is keyed.

Here we group by city but store only the amounts.

using System;
using System.Linq;
using System.Collections.Generic;

record Sale(string City, int Amt);
var sales = new List<Sale> { new("NY", 5), new("NY", 2) };
var g = sales.GroupBy(s => s.City, s => s.Amt);
foreach (var grp in g)
  Console.WriteLine($"{grp.Key}: {string.Join(\",\", grp)}");

Sorting and Grouping Are Deferred

Both OrderBy and GroupBy use deferred execution — they run when enumerated. But note sorting and grouping must consume the whole source to produce the first element.

So unlike Where, they are not streaming; the cost lands on first iteration.

using System;
using System.Linq;

int[] nums = { 3, 1, 2 };
var q = nums.OrderBy(n => n);
Console.WriteLine("Query built");
Console.WriteLine(string.Join(", ", q));

Quick Check

Think about multi-level sorting.

Recap

OrderBy/OrderByDescending sort by a key; ThenBy adds tie-breakers. A second OrderBy re-sorts and is not a tie-breaker.

GroupBy partitions into IGrouping objects with a Key and members, often projected into summaries. Both are deferred but consume the whole source. Next we aggregate and materialize.

Frequently asked questions

Is the “OrderBy and Grouping” lesson free?

Yes — the full text of “OrderBy and Grouping” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “OrderBy and Grouping”?

Sort and group results. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “OrderBy and Grouping” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Where and Filtering
  2. Select and Projection
  3. OrderBy and Grouping
  4. Aggregates and ToList
← Back to C# Academy