typestar

LINQ in depth

17 steps in 6 sets of C#.

LINQ is the reason C# programmers stop writing loops. It arrived in 2007 as a bet that queries belong in the language, not in strings, and the bet paid off twice: once in method chains that read left to right, and again in a query syntax that reads like the SQL it borrowed from. Both compile to the same calls, and both are lazy — nothing runs until something asks for results.

The basics tour sampled Where and Select. This one covers the rest of the working set: flattening with SelectMany, slicing with TakeWhile and Chunk, the three join shapes, the query keywords let and group into, and the materializers that turn a query into the dictionary you actually wanted. The encore joins, groups and ranks its way through two small reporting programs.

Start this tour

Shaping

  • Select with indexThe overload that numbers a list without a counter variable.
  • SelectManyFlatten a sequence of sequences into one stream.
  • ZipWalk parallel sequences in step.

Slicing

  • TakeWhile & SkipWhileCut a sequence at the first element that breaks the rule.
  • ChunkBatch a sequence into arrays of at most n.
  • DistinctByDeduplicate by a key while keeping whole elements.

Joins & lookups

  • JoinThe inner join, matching rows across two sequences on a key.
  • GroupJoinThe left join's cousin: every left row, with its group of matches.
  • ToLookupA frozen one-to-many index over a sequence.

Query syntax

  • Query syntaxThe same LINQ, shaped like the SQL it borrowed from.
  • let clausesName an intermediate value once, use it three times.
  • group ... intoGroup inside a query and keep querying over the groups.

Materializing & sets

Encore

  • sales_report.csJoin, group and rank in one query: a sales table from raw orders.
  • anagram_finder.csGroup words by their sorted letters and the anagrams find themselves.

The other C# tours