How to Use Lambda with LINQ in C# - Simple Guide
In C#, you use
lambda expressions with LINQ to write inline functions that filter, select, or transform data collections. Lambdas are anonymous functions that make LINQ queries concise and easy to read, for example: numbers.Where(n => n > 5) filters numbers greater than 5.Syntax
A lambda expression in LINQ uses the syntax input => expression. Here, input is the parameter, and expression is the operation performed on it.
Common LINQ methods using lambdas include:
Where- filters elements based on a conditionSelect- projects each element into a new formOrderBy- sorts elements
Example syntax:
collection.Method(item => item.Property == value)
csharp
var filtered = collection.Where(item => item.Property == value);Example
This example shows how to use a lambda with LINQ to filter and select numbers greater than 5 from a list.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 3, 6, 8, 2, 10 }; var filteredNumbers = numbers.Where(n => n > 5).Select(n => n * 2); foreach (var num in filteredNumbers) { Console.WriteLine(num); } } }
Output
12
16
20
Common Pitfalls
Common mistakes when using lambdas with LINQ include:
- Forgetting to include
using System.Linq;which enables LINQ methods. - Using incorrect lambda syntax, like missing the
=>operator. - Confusing
Where(filter) withSelect(transform). - Not realizing LINQ queries are deferred and only run when enumerated.
csharp
/* Wrong: Missing lambda arrow */ // var result = numbers.Where(n n > 5); /* Right: Correct lambda syntax */ var result = numbers.Where(n => n > 5);
Quick Reference
| LINQ Method | Purpose | Lambda Example |
|---|---|---|
| Where | Filters elements by condition | n => n > 5 |
| Select | Transforms each element | n => n * 2 |
| OrderBy | Sorts elements ascending | n => n |
| OrderByDescending | Sorts elements descending | n => n |
| FirstOrDefault | Gets first element or default | n => n > 5 |
Key Takeaways
Use lambda expressions as inline functions inside LINQ methods for concise queries.
Remember to include 'using System.Linq;' to access LINQ extension methods.
Common LINQ methods with lambdas are Where (filter) and Select (transform).
Check lambda syntax carefully: it must have 'parameter => expression'.
LINQ queries run only when you iterate over the results, not when declared.