Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 182 ยท Delegates, Events and LINQ

LINQ Operators in Depth

Go beyond Where and Select - GroupBy, Join, GroupJoin, LeftJoin, SelectMany, Zip, Aggregate, set operations, Chunk, CountBy and AggregateBy in C# with runnable examples.

Filtering and projecting get you far, but real reports need more: totals per category, customers matched to orders, a list of lists flattened into one, running totals, pairs of items side by side. This lesson tours the operators that handle those jobs: grouping, joining, flattening, combining sequences, aggregating, set operations and batching. It also covers the operators added in recent .NET versions (CountBy, AggregateBy, Index in .NET 9; LeftJoin and RightJoin in .NET 10).

If you have not yet met Where, Select and OrderBy, read LINQ Basics first. The examples here share two small record types, which every TryIt defines for itself.

GroupBy: one sequence into many

GroupBy splits a sequence into groups that share a key. The result is a sequence of IGrouping<TKey, TElement>; each group is itself a sequence of its elements and has a Key property.

C# GroupBy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Groups appear in the order their keys were first seen, and the elements inside a group keep their original order. There is also an overload that takes a result selector directly: sales.GroupBy(s => s.Region, (key, items) => new { key, Total = items.Sum(i => i.Amount) }).

A grouping is lazy and holds the whole input in memory while it works. Calling ToList() on the group list or using ToLookup gives you something you can index into repeatedly.

CountBy and AggregateBy (.NET 9)

Counting per key is so common that .NET 9 added CountBy. AggregateBy does the same for any running aggregate, without building the groups at all, which is cheaper:

C# CountBy and AggregateBy (.NET 9)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both return a sequence of KeyValuePair<TKey, TValue>, which deconstructs into (key, value) as the loop shows. These operators exist only on .NET 9 and later; on older targets use GroupBy(...).Select(g => (g.Key, g.Count())).

Join: matching two sequences

Join is an inner join like in SQL: it pairs each element of the first sequence with the elements of the second that have an equal key. Elements without a partner disappear.

C# Join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Join builds a hash table of the second sequence once, so it runs in roughly linear time instead of comparing every pair. The output order follows the first (outer) sequence.

GroupJoin: each left item with its list of matches

GroupJoin keeps every element of the first sequence and pairs it with the (possibly empty) group of matching elements from the second. It is the building block of a left join and of nested results like "customer with a list of orders":

C# GroupJoin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

LeftJoin and RightJoin (.NET 10)

Before .NET 10 a flat left join took the awkward pattern GroupJoin plus SelectMany plus DefaultIfEmpty. .NET 10 added LeftJoin and RightJoin. Unmatched sides are passed to your result selector as default (usually null):

C# LeftJoin and RightJoin (.NET 10)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

For the old pattern, still common in existing code, see the read-only snippet:

C#
// Pre-.NET 10 left join (read-only)
var left = customers
    .GroupJoin(orders, c => c.Id, o => o.CustomerId, (c, os) => new { c, os })
    .SelectMany(x => x.os.DefaultIfEmpty(), (x, o) => new { x.c.Name, Item = o?.Item ?? "-" });

LeftJoin and RightJoin exist for LINQ to Objects in .NET 10. Query providers such as EF Core translate their own forms to SQL, so check your provider's documentation before using them there.

SelectMany: flattening

Select with a function that returns a list gives you a list of lists. SelectMany flattens one level:

C# SelectMany

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Use the second overload (with a result selector) whenever you still need information from the outer element. The cross-product at the end is the LINQ equivalent of two nested loops.

Zip and Index: walking in step

Zip combines two (or three) sequences element by element. It stops at the shorter one:

C# Zip and Index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last score (60) is dropped because there is no matching name. Index() replaces the old trick Select((x, i) => (i, x)).

Aggregate: the general fold

Sum, Max and Count are special cases of Aggregate, which carries an accumulator through the sequence. You give a function that takes the accumulator and the next element and returns the new accumulator. An optional seed is the starting value:

C# Aggregate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Always give a seed if the sequence can be empty. When a specific operator exists (Sum, Max, string.Join), use it: it communicates intent better than Aggregate, and string.Join is far faster than concatenating strings in a fold.

Set operations

These treat sequences like mathematical sets and remove duplicates from the result:

C# Union, Intersect, Except

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Union, Intersect and Except use the element type's equality. For your own class, that means reference equality unless you override Equals/GetHashCode, or you use a record (value equality) or the *By versions with a key. Concat is the only one that keeps duplicates.

Chunk: batching

Chunk(size) (.NET 6) splits a sequence into arrays of at most size elements. Handy for batch processing, paging in a console, or sending items in groups of 100:

C# Chunk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last chunk can be smaller. Each chunk is a new array, so changing it does not affect the source.

Other useful operators

A few more that earn their place:

  • DefaultIfEmpty() and DefaultIfEmpty(value) return a one-element sequence holding a default when the source is empty. Handy before Max() or Average().
  • Append / Prepend add one element at the end or start.
  • OfType<T>() filters by runtime type; Cast<T>() converts every element and throws on a mismatch.
  • Zip, Concat and Chunk never reorder; OrderBy, GroupBy, Join and Distinct have the ordering rules above.
  • TakeLast, SkipLast and Take(range) slice from the end.
C# OfType, DefaultIfEmpty, Append, TakeLast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choosing the right operator

I want to... Use
Count items per key CountBy (.NET 9) or GroupBy + Count
Totals per key without keeping the groups AggregateBy or GroupBy + Sum
Pair two lists on a shared key, dropping unmatched Join
Keep every left item, even unmatched LeftJoin (.NET 10) or GroupJoin
Flatten a list of lists SelectMany
Process two lists in lockstep Zip
Remove duplicates Distinct / DistinctBy
Process in batches Chunk
A running total, or anything custom Aggregate (or a loop)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does customers.Join(orders, c => c.Id, o => o.CustomerId, ...) do with a customer who has no orders?

    Join only produces pairs that match. To keep customers without orders use GroupJoin, or LeftJoin on .NET 10.
  2. 2. What is the difference between Select and SelectMany when the selector returns a list?

    Select yields one list per element (a sequence of lists). SelectMany concatenates all the inner lists into one flat sequence.
  3. 3. new[] {1,2,3}.Zip(new[] {10,20}) produces how many pairs?

    Zip stops at the end of the shorter sequence, so you get (1,10) and (2,20) and the 3 is dropped.
  4. 4. Which statement about GroupBy results is true?

    GroupBy returns IEnumerable of IGrouping. Keys appear in first-seen order and elements keep their original order inside each group. It is lazy, not a Dictionary.
  5. 5. Why should you provide a seed to Aggregate when the source might be empty?

    The seedless overload uses the first element as the starting accumulator, so with no elements there is nothing to return and it throws. A seed gives a defined result.

Summary

  • GroupBy splits a sequence into IGrouping groups with a Key; CountBy and AggregateBy (.NET 9) are cheaper when you only need per-key numbers.
  • Join is an inner join; GroupJoin pairs each left element with its group of matches; LeftJoin and RightJoin (.NET 10) give flat outer joins.
  • SelectMany flattens nested collections and builds cross-products.
  • Zip walks sequences in step and stops at the shorter; Index() (.NET 9) pairs elements with their position.
  • Aggregate is the general fold; provide a seed for possibly empty input and prefer specific operators when they exist.
  • Union, Intersect, Except and Distinct rely on equality; the *By versions take a key selector. Chunk batches into arrays.

Next: Deferred Execution and LINQ Pitfalls