How LINQ behaves: deferred execution, grouping and joins
Deferred execution
Most operators that return a sequence (Where, Select, OrderBy, GroupBy, Join) do no work when called. They return an object that describes the query, and the work happens when someone enumerates it: foreach, ToList, Count, First, Sum and similar operators run the query immediately.
var list = new List<int> { 1, 2, 3 };
var query = list.Where(n => n > 1);
list.Add(4);
query.Count(); // 3: the filter runs now and sees 4Three consequences follow.
Captured variables are read at enumeration time. A lambda captures the variable, not its value. If you change threshold after building Where(n => n > threshold), the query uses the new value. A for loop has a single loop variable, so queries built in the loop all see its final value; copy it into a local inside the loop or materialize with ToList() there. foreach creates a fresh variable on each iteration.
Every enumeration runs the query again. Calling Sum() and then Max() on the same Select runs the selector twice per element. With File.ReadLines or a database query, each Any, Count and foreach re-reads the source, and the data may change in between. Materialize once with ToList() when you need the results more than once.
Side effects in Select are unreliable. Logging or writing inside a selector may not happen at all (never enumerated) or happen several times (enumerated repeatedly). Keep lambdas pure and do side effects in a foreach.
Finally, a deferred query reads its source through the source's enumerator. Modifying a List<T> while a Where over it is being enumerated throws InvalidOperationException ("Collection was modified"). Use .ToList() before the loop or list.RemoveAll(...).
Grouping
GroupBy returns groups in the order their keys first appear in the source; keys are not sorted. It is deferred and regroups on every enumeration.
ToLookup runs immediately and builds an immutable ILookup<TKey, TElement>. Its indexer returns an empty sequence for a missing key instead of throwing, which makes it handy for repeated lookups.
var byCustomer = orders.ToLookup(o => o.CustomerId);
var none = byCustomer[999]; // empty, no KeyNotFoundExceptionJoins
Join is an inner join: one result per matching pair, and unmatched outer elements disappear. A left join is GroupJoin followed by SelectMany over DefaultIfEmpty():
var rows = from c in customers
join o in orders on c.Id equals o.CustomerId into co
from o in co.DefaultIfEmpty()
select new { c.Name, Total = o?.Total ?? 0 };For a class, o is null for customers without orders, so guard member access. For a value type such as a tuple, o is default and its fields are zero. (.NET 10 also adds a dedicated LeftJoin method.)
Flattening, pairing, folding
SelectManyflattens:teams.Select(t => t.Members)gives a sequence of arrays,teams.SelectMany(t => t.Members)gives one sequence of members.Zippairs elements by position and stops at the end of the shorter sequence. Different lengths are not an error.Aggregatefolds a sequence. Without a seed, the first element is the initial accumulator, and an empty sequence throws. With a seed, accumulation starts from the seed.
new[] { "a", "b", "c" }.Aggregate((acc, x) => x + acc); // "cba"
new[] { "a", "b", "c" }.Aggregate(">", (acc, x) => acc + x); // ">abc".NET 6+ helpers
MaxBy/MinBycompare by a key but return the whole element; only the key must be comparable.DistinctBykeeps the first element seen for each key.Chunk(n)splits a sequence into arrays ofn; the final array may be shorter and is kept.
Ordering rules
Enumerable.OrderBy is a stable sort: elements with equal keys keep their source order. (List<T>.Sort is not stable, and databases make no promise either.) Calling OrderBy twice starts a new sort, so the second key becomes the primary one. Use ThenBy for secondary keys.
IEnumerable vs IQueryable
IQueryable<T> (for example an EF Core DbSet<T>) inherits IEnumerable<T>, but its operators come from Queryable and take Expression<Func<...>>. The provider reads those expression trees and translates them to SQL when the query is enumerated.
Extension methods are chosen by the static type. Assigning db.Orders to an IEnumerable<Order> variable makes the next Where an Enumerable.Where: EF sends a SELECT without WHERE and the filter runs in memory on every row. Keep queries typed as IQueryable<T> (or var) until you deliberately want in-memory processing. Only constructs the provider understands can be translated; arbitrary C# methods cannot.