Array Methods → LINQ
Querying and transforming collections
Introduction
In this lesson, you'll learn about array methods → linq in C#. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with querying and transforming collections.
C# has its own approach to querying and transforming collections, which we'll explore step by step.
The C# Way
Let's see how C# handles this concept. Here's a typical example:
using System.Linq;
var nums = new[] { 1, 2, 3, 4, 5, 6 };
var doubled = nums.Select(n => n * 2);
var evens = nums.Where(n => n % 2 == 0);
int total = nums.Sum(); // or .Aggregate((a,b) => a+b)
int? first = nums.FirstOrDefault(n => n > 3);
bool anyBig = nums.Any(n => n > 5);
bool allPos = nums.All(n => n > 0);
var sorted = nums.OrderByDescending(n => n);
// Chaining
int result = nums
.Where(n => n % 2 == 0)
.Select(n => n * n)
.Sum();Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
const nums = [1, 2, 3, 4, 5, 6];
const doubled = nums.map(n => n * 2);
const evens = nums.filter(n => n % 2 === 0);
const total = nums.reduce((a, b) => a + b, 0);
const first = nums.find(n => n > 3);
const anyBig = nums.some(n => n > 5);
const allPos = nums.every(n => n > 0);
const sorted = [...nums].sort((a, b) => b - a);
// Chaining
const result = nums
.filter(n => n % 2 === 0)
.map(n => n * n)
.reduce((a, b) => a + b, 0);You may be used to different syntax or behavior.
JS .map() → C# .Select(); JS .filter() → C# .Where()
You may be used to different syntax or behavior.
JS .reduce() → C# .Aggregate() or specific methods (Sum, Max, etc.)
You may be used to different syntax or behavior.
JS .find() → C# .FirstOrDefault()
You may be used to different syntax or behavior.
JS .some()/.every() → C# .Any()/.All()
Step-by-Step Breakdown
1. Core LINQ Methods
LINQ method names differ from JS but map one-to-one: Select=map, Where=filter, Aggregate=reduce.
nums.map(n => n*2).filter(n => n>3)nums.Select(n => n*2).Where(n => n>3)2. Specialized Aggregates
LINQ has Sum, Min, Max, Average, Count built-in — no need to write reduce for common operations.
nums.reduce((a,b) => a+b, 0)nums.Sum() // also: .Min(), .Max(), .Average()3. Query Syntax
LINQ also has SQL-like query syntax as an alternative to method chaining.
var result = from n in nums
where n % 2 == 0
select n * n;Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- JS .map() → C# .Select(); JS .filter() → C# .Where()
- JS .reduce() → C# .Aggregate() or specific methods (Sum, Max, etc.)
- JS .find() → C# .FirstOrDefault()
Key Takeaways
- map → Select, filter → Where, reduce → Aggregate/Sum
- find → FirstOrDefault, some → Any, every → All
- LINQ has specialized Sum/Min/Max/Average methods
- Both method chaining and SQL-like query syntax available