Where, Select and ordering
Where, Select and ordering
LINQ to Objects is a set of query operations for in-memory sequences. Where keeps matching items, Select produces a result for each item, and OrderBy arranges results by a key. These operators return sequences rather than editing the original collection.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Filter and project
Where takes a Boolean predicate; Select takes a transformation. Chain them in the order that expresses the desired result. The following extension methods are available through using System.Linq;.
using System;using System.Linq;int[] stock = { 0, 3, 1, 0, 5 };var labels = stock.Where(n => n > 0).Select(n => $"Stock {n}");Console.WriteLine(string.Join(", ", labels));Console.WriteLine(string.Join(",", stock));The filter removes zero quantities from the result, the projection makes three labels, and the original array remains unchanged.
Expected output (reasoned, not executed):
Stock 3, Stock 1, Stock 50,3,1,0,5Sort by primary and secondary keys
OrderBy creates an ascending primary order; OrderByDescending reverses it. ThenBy adds a secondary key within ties, while a new OrderBy establishes a new primary order. For predictable identifier ordering use StringComparer.Ordinal rather than relying on current culture.
using System;using System.Linq;var books = new[] { (Name: "Zoo", Quantity: 2), (Name: "Atlas", Quantity: 2), (Name: "Map", Quantity: 4), (Name: "Sky", Quantity: 0) };var names = books.Where(b => b.Quantity > 0) .OrderByDescending(b => b.Quantity) .ThenBy(b => b.Name, StringComparer.Ordinal) .Select(b => b.Name);Console.WriteLine(string.Join(",", names));Map has the highest quantity. Atlas precedes Zoo because their quantities tie and ordinal name sorting breaks the tie.
Expected output (reasoned, not executed):
Map,Atlas,ZooCompare query and method syntax
Query syntax uses from, where, orderby and select clauses. The compiler translates supported clauses into method calls; both forms can express the same in-memory query. SelectMany flattens nested sequences instead of returning one nested collection per item.
using System;using System.Linq;int[] scores = { 3, 1, 4, 2 };var query = from n in scores where n >= 3 orderby n select n * 10;var methods = scores.Where(n => n >= 3).OrderBy(n => n).Select(n => n * 10);Console.WriteLine(string.Join(",", query));Console.WriteLine(query.SequenceEqual(methods));int[][] shelves = { new[] { 1, 2 }, Array.Empty<int>(), new[] { 3 } };Console.WriteLine(string.Join(",", shelves.SelectMany(s => s)));Both query forms produce equal sequences. SelectMany visits each nested array in order; an empty inner array contributes nothing.
Expected output (reasoned, not executed):
30,40True1,2,3Common mistakes and edge cases
Use ThenBy for tie-breaking, not a second OrderBy. Where does not remove items from the original list. Projection is not automatically a deep copy: selecting an object can preserve its reference. These examples use Enumerable methods, not database translation. Query definitions usually defer execution; the deferred-execution lesson explains when values are read.
Practice and recap
Filter quantities [4,0,2,4,1] to at least 2, sort descending and project each to twice its value. Compare query syntax with method syntax; repeat using an empty array.
Hint: Filter before mapping, and use OrderByDescending.
Learning objective: Trace a LINQ pipeline on known values. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Where, Select and ordering — knowledge check
Apply the lesson concepts to the following scenarios.
Which operator keeps only matching elements?
What does Select(n => n * 2) do?
Which method adds a tie-breaker to OrderBy?
What does SelectMany do to [[1,2],[],[3]]?
Which namespace supplies standard in-memory LINQ extension methods?