LINQ: method syntax
The same query twice
The previous lesson wrote queries as from ... where ... select. The method form is the same thing with the translation the compiler writes spelled out by hand: extension methods from System.Linq.Enumerable, each taking a lambda. Where takes Func<T, bool>, OrderBy takes Func<T, TKey> and Select takes Func<T, TResult>. Reading the signatures of those three covers most of LINQ.
var cities = new[] { "Oslo", "Lima", "Kyiv", "Rome", "Baku", "Pune", "Cork" };
var queryForm =
from city in cities
where city.Length == 4
orderby city
select city.ToUpperInvariant();
var methodForm = cities
.Where(city => city.Length == 4)
.OrderBy(city => city)
.Select(city => city.ToUpperInvariant());
Console.WriteLine($"same: {queryForm.SequenceEqual(methodForm)}");
Console.WriteLine(string.Join(" ", methodForm));
dotnet run
same: True
BAKU CORK KYIV LIMA OSLO PUNE ROME
SequenceEqual walks both sequences and compares
element by element, so True is a real answer about
the values and not about the two expressions looking alike.
string.Join then walks the second one again: a
query can be enumerated as often as the source allows.
The chain reads top to bottom in the order the data flows, which is the
main reason to prefer it for a short pipeline. The query form reads better
once there is a let, a
join or a group ... into,
because the method form of those needs a lambda that returns a lambda.
OrderBy and ThenBy
Sorting by more than one key is two calls: OrderBy then ThenBy. ThenBy exists only on IOrderedEnumerable<T>, the type OrderBy returns, so the compiler refuses a ThenBy that has no primary sort:
var orders = new[]
{
("EU", 3, 12.50m), ("US", 1, 40.00m), ("EU", 1, 8.25m),
("US", 3, 5.00m), ("EU", 2, 19.90m),
};
var report = orders
.OrderBy(order => order.Item1)
.ThenByDescending(order => order.Item3)
.Select(order => $"{order.Item1} #{order.Item2} {order.Item3:F2}");
Console.WriteLine(string.Join(Environment.NewLine, report));
dotnet run
EU #2 19.90
EU #3 12.50
EU #1 8.25
US #1 40.00
US #3 5.00
Region first, amount within a region, largest first. The
m suffix on the amounts makes them
decimal, so F2 prints two
digits exactly and the sort compares decimal values, not their printed
form.
A second OrderBy would not do the same thing: it
starts a new primary sort and throws the first one away. The compiler
accepts it, because it is a legal call on a sequence, and the result is
simply sorted by the second key alone.
A source that is not a collection
Every LINQ method takes an IEnumerable<T>, and a sequence does not have to exist in memory before the query starts. Enumerable.Range produces numbers on demand, and the pipeline below never builds an array of them:
var squares = Enumerable.Range(1, 10)
.Where(n => n % 2 == 1)
.Select(n => n * n);
Console.WriteLine(string.Join(", ", squares));
Console.WriteLine($"count: {squares.Count()}");
dotnet run
1, 9, 25, 49, 81
count: 5
The odd numbers of 1 to 10 are 1, 3, 5, 7 and 9, and their squares are the five values printed. The pipeline is a description: nothing multiplies until string.Join walks it, and the second walk for Count() produces the squares again.
Which form to write
Both forms compile to the same calls, so there is no performance argument and no correctness argument between them. What is left is how the code reads to the next person:
- A short pipeline of filter, sort and project reads well as a chain, and a chain is the only shape available when the source is passed to a method.
- let, a second from and join ... into read better in query syntax; the method form of a join takes a lambda returning a lambda.
- Mixing is legal and common: a query expression whose source is a method call, or a chain whose first step is a query variable.
A team that has both forms in one file is not inconsistent; a team that chooses one form for each situation and writes the rule down is easier to read. The rule in this course is the one above.
Exercises
- Write the cities query with a Func<string, bool> variable instead of an inline lambda and pass it to Where.
- Sort the orders by region and then by the order number, and print the result.
- Replace Enumerable.Range(1, 10) with an array of the same numbers. Which lines change?
- Try orders.ThenBy(o => o.Item2) without an OrderBy. Read the error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
cities.Where(c => c.Length == 4)return?Answer
A sequence that yields the matching cities when it is enumerated
Where returns a lazy IEnumerable<T>, so nothing is filtered until the result is walked.
-
Which call sorts by a second key after a primary sort?
Answer
ThenBy
ThenBy is defined on IOrderedEnumerable<T>, the type OrderBy returns, so it keeps the primary order.
-
What does this program print?
var n = new[] { 1, 2, 3, 4 }; var q = n.Where(x => x % 2 == 0).Select(x => x * 10); Console.WriteLine(string.Join(",", q));Answer
20,40
The filter keeps 2 and 4, and the projection multiplies each by ten.
-
What is the parameter of Where?
Answer
Func<T, bool>
Where needs a predicate: a function from an item to a bool.
-
What does SequenceEqual compare?
Answer
The elements of two sequences, in order
It walks both sequences in step and compares each pair, so the order matters.
-
Why does
ThenBynot compile afterSelect?Answer
Select returns IEnumerable<T>, which has no ThenBy
Only IOrderedEnumerable<T> offers ThenBy, and Select returns a plain sequence.
-
What does
Enumerable.Range(1, 3)produce?Answer
The numbers 1, 2 and 3
Range takes a start value and a count, so it starts at 1 and yields three items.
-
What does this program print?
var s = new[] { "a", "bb", "ccc" }; Console.WriteLine(s.OrderBy(x => x.Length).First());Answer
a
The shortest string sorts first, and First takes the first element of the sorted sequence.
-
Where do Where, Select and OrderBy come from?
Answer
Extension methods in System.Linq.Enumerable
They are static extension methods of Enumerable, which is why a using of System.Linq is needed without ImplicitUsings.
-
Which form is better for a query with
letandgroup ... into?Answer
Query syntax, because the method form needs a lambda returning a lambda
The clauses with a continuation translate into nested lambdas that are hard to read as a chain.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev