Lesson 2: LINQ Method Syntax & Extension Methods
LINQ method syntax is the most common way to write LINQ queries in C#. It uses extension methods defined in System.Linq, making queries fluent and easy to chain.
Using Extension Methods
Most LINQ operations are extension methods on IEnumerable<T>. That means you can call them directly on collections like arrays, lists, and query results.
using System.Linq;
var words = new[] { "apple", "banana", "grape", "avocado" };
var startsWithA = words
.Where(w => w.StartsWith("a"))
.OrderBy(w => w.Length)
.Select(w => w.ToUpper());
foreach (var fruit in startsWithA)
{
Console.WriteLine(fruit);
}
Common Method Syntax Operators
These operators are the building blocks for most LINQ queries:
Where— filter items.Select— project each item into a new form.OrderBy/OrderByDescending— sort results.GroupBy— group items by a key.Join— combine related collections.
Lambda Expressions
LINQ method syntax typically uses lambdas to define predicates and projections. Lambdas are small anonymous functions written with =>.
var prices = new List<decimal> { 12.50m, 7.99m, 19.95m, 3.49m };
var expensive = prices.Where(price => price > 10.00m);
var rounded = prices.Select(price => Math.Round(price));
Chaining Queries
The real power of method syntax is chaining multiple operators in a single expression.
var result = words
.Where(w => w.Length > 5)
.OrderByDescending(w => w)
.Select(w => new { Text = w, Length = w.Length });
🧠 Quick Check — Lesson 2
Which LINQ operator is used to transform each item in a sequence?
LINQ and In-Memory Collections
LINQ method syntax is perfect for filtering lists, arrays, dictionaries, and any sequence that implements IEnumerable<T>.
| Operator | Use |
|---|---|
Where | Filter items by condition |
Select | Transform each item |
OrderBy | Sort ascending |
GroupBy | Group items by key |
Lesson Summary
Method syntax uses chained extension methods to build LINQ queries in a fluent style.
Common operators include Where, Select, OrderBy, and GroupBy.
Lambdas provide compact predicates and projections using =>.
LINQ method syntax works with any IEnumerable<T> collection once you import System.Linq.