How to Use LINQ in C#: Simple Syntax and Examples
LINQ in C# lets you query collections using
from, where, and select keywords in a readable way. You write queries like SQL but directly in C# to filter, sort, or transform data easily.Syntax
LINQ queries use a simple pattern with these parts:
- from: defines the data source and a variable for each item
- where: filters items based on a condition
- select: chooses what to return from each item
This pattern reads like a sentence and works on arrays, lists, or any collection.
csharp
var result = from item in collection where item.Property > 10 select item;
Example
This example shows how to use LINQ to find even numbers from a list and print them.
csharp
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 }; var evenNumbers = from num in numbers where num % 2 == 0 select num; foreach (var n in evenNumbers) { Console.WriteLine(n); } } }
Output
2
4
6
Common Pitfalls
Common mistakes when using LINQ include:
- Forgetting to include
using System.Linq;which is required for LINQ methods. - Confusing query syntax with method syntax (both work but have different forms).
- Not realizing LINQ queries are lazy and only run when you iterate or convert to a list.
Here is a wrong and right way to use LINQ:
csharp
// Wrong: Missing using directive // var evens = numbers.Where(n => n % 2 == 0); // Error if System.Linq not included // Right: using System.Linq; var evens = numbers.Where(n => n % 2 == 0);
Quick Reference
| LINQ Keyword/Method | Purpose |
|---|---|
| from | Start query and define data source |
| where | Filter items by condition |
| select | Choose what to return |
| OrderBy | Sort items ascending |
| OrderByDescending | Sort items descending |
| GroupBy | Group items by key |
| Join | Combine two collections |
| ToList | Convert query result to list |
| FirstOrDefault | Get first item or default if none |
Key Takeaways
LINQ lets you write readable queries directly in C# to work with collections.
Use
from, where, and select keywords to build queries.Always include
using System.Linq; to access LINQ features.LINQ queries run only when you iterate or convert them, so they are lazy by default.
You can use both query syntax and method syntax depending on your preference.