Neither LINQ nor foreach is always faster. LINQ improves composition, but delegates, iterators, and allocations can matter in a hot loop. foreach is often faster for simple in-memory work; IQueryable LINQ can be far faster because filtering runs in the database. Example: decimal total = 0; foreach (var item in items) if (item.Active) total += item.Price; Measure realistic data with BenchmarkDotNet, use Release builds, and consume results so the optimizer cannot remove work. First optimize algorithms, database round trips, and allocations. Choose the clearest implementation unless profiling identifies this code as a bottleneck.
Backbencher Developer · · 0 likes