Compose a LINQ filter, sort and projection

A LINQ pipeline can filter values, order them and produce a different representation without changing the source collection. Query syntax and method syntax express the same sequence of operations here.

Use explicit comparison and casing rules when the result must be independent of the machine's current culture.

Compare both forms

Create a .NET console project and use this Program.cs:

C#
string[] names = ["Grace", "Alan", "Linus", "Ada"];
var method = names.Where(x => x.Length == 5)
	.OrderBy(x => x, StringComparer.Ordinal)
	.Select(x => x.ToUpperInvariant());
var query = from name in names
			where name.Length == 5
			orderby name
			select name.ToUpperInvariant();
Console.WriteLine(string.Join(", ", method));
Console.WriteLine(string.Join(", ", query));

For these ASCII names, both lines print GRACE, LINUS. The method form explicitly selects ordinal ordering. Query syntax's plain orderby uses the default comparer and can differ for other text or cultures.

Decide when to execute

The pipeline is evaluated when enumerated. Changing a mutable source before enumeration can change the result. Call ToArray() or ToList() when you deliberately need a snapshot or will reuse a costly result.

Keep predicates and projections free of side effects. A later enumeration may execute them again. With an IQueryable database provider, supported expressions become a server query. Switching to AsEnumerable() or materializing changes where subsequent work occurs. Treat that boundary as a performance and correctness decision.

Official references

Introduction to LINQ Queries - C#
LINQ offers a consistent model for queries on data across various kinds of data sources and formats. In a LINQ query, you're always working with objects.
https://learn.microsoft.com/en-us/dotnet/csharp/linq/get-started/introduction-to-linq-queries
LINQ query execution

Author: Herman Schoenfeld