C# LINQ Tutorial: Complete Guide with Examples and Best Practices
LINQ (Language Integrated Query) is a feature in C# that allows you to query and manipulate data from collections, arrays, databases, and XML using a consistent syntax.
LINQ simplifies data querying by providing a unified way to filter, project, and transform data directly within C#. Instead of writing complex loops, LINQ allows you to express queries in a declarative style. It supports two syntax styles: query syntax (similar to SQL) and method syntax (using extension methods). LINQ improves readability and reduces boilerplate code, making data processing more efficient and maintainable.
When is LINQ Needed?
Use LINQ when:
• Filtering or searching collections
• Transforming data (mapping one type to another)
• Sorting or grouping data
• Working with arrays, lists, or dictionaries
• Querying databases (via Entity Framework)
How to Use LINQ?
LINQ can be used in two ways:
Query Syntax Example
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List numbers = new List { 1, 2, 3, 4, 5 };
var result = from n in numbers
where n > 2
select n;
foreach (var num in result)
{
Console.WriteLine(num);
}
}
}
Method Syntax Example
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List numbers = new List { 1, 2, 3, 4, 5 };
var result = numbers.Where(n => n > 2).Select(n => n);
foreach (var num in result)
{
Console.WriteLine(num);
}
}
}
Sample Code Snippet
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List names = new List { "Alice", "Bob", "Charlie" };
var filtered = names
.Where(n => n.StartsWith("A"))
.ToList();
Console.WriteLine(filtered.Count);
}
}
Advantages and Disadvantages
| Advantages | Disadvantages |
|---|---|
| Improves code readability | Can reduce performance if misused |
| Reduces need for loops | Harder to debug complex queries |
| Works with multiple data sources | Overuse can make code less explicit |
| Supports method chaining | Learning curve for beginners |
Similar and Alternative Options
| Option | Description | When to Use |
|---|---|---|
| foreach loops | Manual iteration over collections | Simple operations |
| for loops | Index-based iteration | When index access is needed |
| SQL queries | Database-level querying | Direct database operations |
| Lambda expressions | Inline function expressions | Used within LINQ methods |
Common Mistakes
• Overusing LINQ for simple operations where loops are clearer
• Ignoring performance impact of multiple chained queries
• Forgetting to call .ToList() when needed
• Writing overly complex LINQ expressions
• Not understanding deferred execution
• Using LINQ without understanding underlying collections