C# LINQ vs JavaScript map, filter and reduce
On this page
Learning Objective
Use the core .NET collections and translate the array methods you know, map, filter, reduce, find, and sort, into LINQ, and explain deferred execution and the multiple-enumeration bug so you can read queries that later become SQL.
Concept Explanation
JavaScript gives you two workhorse collections: arrays and objects. .NET offers a family, each with a clear purpose. List of T is the growable array you will use most. Dictionary of TKey and TValue is a hash map with fast lookup by key, comparable to a JavaScript Map. HashSet of T stores unique items with fast membership tests. Arrays exist too but have a fixed size. Behind them all sits IEnumerable of T, the interface meaning something you can loop over. Methods that accept IEnumerable of T work with every collection, and returning IReadOnlyList of T from your own methods tells callers they cannot change the result.
LINQ, which stands for Language Integrated Query, is a set of extension methods on IEnumerable of T that mirror the array methods you already use. Select is map, Where is filter, Aggregate is reduce, FirstOrDefault is find, OrderBy is sort, Any is some, All is every, and Sum, Count, Min, and Max cover common reductions. GroupBy has no direct array equivalent but resembles Object.groupBy. Because these are chainable, you will write pipelines that read almost identically to a TypeScript array chain. This matters beyond convenience: in Phase 4, Entity Framework Core translates the same LINQ syntax into SQL, so the skill transfers straight to database queries.
The most important behavioral difference is deferred execution. A JavaScript map runs immediately and returns a new array. A LINQ query like Where or Select does not run when you write it; it builds a description of the work, and the work happens only when something enumerates the result, for example a foreach loop, ToList, Count, or First. That is efficient because you can build a pipeline and stop early, and it is what allows a database provider to convert the whole chain into one SQL statement. It also creates a classic bug: if you enumerate the same deferred query twice, the work runs twice, and if the underlying data changed in between, you get different results.
Two habits prevent most LINQ trouble. First, materialize a query with ToList or ToArray when you need a stable snapshot or intend to use the result more than once. Second, prefer methods that state your assumption: Single throws if there is not exactly one match, First throws if there are none, and the OrDefault variants return null or the default value instead. Choosing deliberately, and handling the empty case, avoids unhandled exceptions and the wrong-data bugs that arise when code assumes a record exists.
| Task | JavaScript or TypeScript | C# LINQ |
|---|---|---|
| Transform each item | items.map(x => x.name) | items.Select(x => x.Name) |
| Keep matching items | items.filter(x => x.done) | items.Where(x => x.Done) |
| Fold to one value | items.reduce((a, x) => a + x.n, 0) | items.Sum(x => x.N) or Aggregate |
| First match or nothing | items.find(x => x.id === 5) | items.FirstOrDefault(x => x.Id == 5) |
| Sort | [...items].sort((a, b) => a.n - b.n) | items.OrderBy(x => x.N) |
| Any or every | items.some(...), items.every(...) | items.Any(...), items.All(...) |
Worked Example: A Pipeline, Deferred Execution and Its Trap
The first block shows a realistic pipeline over in-memory tasks. The second demonstrates deferred execution: a query defined before the data changes reflects the new data when finally enumerated, and enumerating twice does the work twice.
public record WorkItem(int Id, string Title, bool Done, int Priority, string Owner);
var tasks = new List<WorkItem>
{
new(1, "Write report", false, 2, "amy"),
new(2, "Review PR", false, 1, "raj"),
new(3, "Deploy", true, 1, "amy"),
};
// map + filter + sort + take, exactly like an array chain
var openTitles = tasks
.Where(t => !t.Done)
.OrderBy(t => t.Priority)
.Select(t => t.Title)
.ToList(); // materialize: runs the query now
var perOwner = tasks
.GroupBy(t => t.Owner)
.ToDictionary(g => g.Key, g => g.Count()); // { amy: 2, raj: 1 }
// Deferred execution
var highPriority = tasks.Where(t => t.Priority == 1); // nothing has run yet
tasks.Add(new(4, "Fix bug", false, 1, "raj")); // change the source
Console.WriteLine(highPriority.Count()); // 3, includes the new task
// The multiple-enumeration trap
var expensive = tasks.Where(t => SlowCheck(t)); // deferred
if (expensive.Any()) // runs the whole query
{
foreach (var t in expensive) { } // runs it again
}
var safe = tasks.Where(t => SlowCheck(t)).ToList(); // run once, reuse safelyRead the pipeline aloud and it matches the JavaScript version step for step. The trap is the part with no JavaScript analog, because a JavaScript array method always returns a finished array.
Real-World Examples
- LINQ shipped with C# 3.0 and the .NET Framework 3.5 in November 2007, designed under Anders Hejlsberg's language team. Its central idea, one query syntax that works over in-memory collections, XML, and databases, is the reason the same Where and Select calls you learn here later become SQL through Entity Framework Core.
- Multiple enumeration is a common cause of production performance incidents in .NET services, and the standard static analyzers flag it with a dedicated warning for exactly this reason. A query bound to a database that gets enumerated twice sends two SQL statements, which under load doubles database work for no benefit.
Review Questions & Answers
A JavaScript filter runs immediately and returns a finished array. A LINQ Where returns a query object that does no work until something enumerates it, such as ToList, foreach, or Count. This lets you compose queries cheaply and lets a database provider translate the whole chain into one SQL statement, but it also means the results depend on when the enumeration happens.
Each enumeration re-executes the query against the current state of the source. If the data changed in between, the two passes can return different results, which produces inconsistent logic such as a count that disagrees with the loop that follows. If the source is a database or a network call, it also repeats the work and any side effects. Calling ToList once creates a stable snapshot.
Single asserts that exactly one item matches and throws if there are zero or several, which surfaces data problems such as a duplicated key immediately. First only requires at least one match and silently picks the first of many, hiding duplicates. Use Single when uniqueness is an invariant, and the OrDefault variants when absence is a normal outcome you will handle explicitly.
The query runs at enumeration time, after the context is gone, so it fails with an object disposed error or returns nothing useful. The fix is to materialize inside the method with ToListAsync or an equivalent, and return a concrete list. Returning deferred queries across the boundary of a resource that has a limited lifetime is a well-known source of runtime errors.