Mastering LINQ: 10 Practical C# Examples Every .NET Developer Should Know
LINQ (Language Integrated Query) is one of the most powerful features in .NET. It lets you query collections, databases, XML, and more using a consistent, readable syntax directly inside C#. Instead of writing verbose loops and conditionals, you can express what you want, not how to get it.
Get Santanu Chandra’s stories in your inbox
Join Medium for free to get updates from this writer.
In this article, we’ll walk through 10 practical, real-world LINQ examples — from simple filtering to advanced grouping and joins — that you can copy, run, and adapt in your own projects.
1. Filtering Data with Where
The most common LINQ operation — pulling out items that match a condition.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
Console.WriteLine(string.Join(", ", evenNumbers));
// Output: 2, 4, 6, 8, 10Use case: Filtering active users, in-stock products, or valid records.
2. Projecting Data with Select
Transform each item in a collection into a new shape.
List<string> names = new List<string> { "alice", "bob", "charlie" };
var capitalized = names.Select(n => char.ToUpper(n[0]) + n.Substring(1)).ToList();
Console.WriteLine(string.Join(", ", capitalized));
// Output: Alice, Bob, CharlieUse case: Converting entities into DTOs (Data Transfer Objects) for APIs.
3. Sorting with OrderBy and OrderByDescending
List<Product> products = new List<Product>
{
new Product { Name = "Laptop", Price = 1200 },
new Product { Name = "Mouse", Price = 25 },
new Product { Name = "Monitor", Price = 300 }
};
var sortedByPrice = products.OrderBy(p => p.Price).ToList();
var sortedDesc = products.OrderByDescending(p => p.Price).ToList();
foreach (var p in sortedByPrice)
Console.WriteLine($"{p.Name}: ${p.Price}");Use case: Sorting product listings, leaderboards, or search results.
4. Grouping Data with GroupBy
Group related items together — great for reports and summaries.
List<Employee> employees = new List<Employee>
{
new Employee { Name = "John", Department = "IT" },
new Employee { Name = "Sarah", Department = "HR" },
new Employee { Name = "Mike", Department = "IT" },
new Employee { Name = "Anna", Department = "HR" }
};
var groupedByDept = employees.GroupBy(e => e.Department);
foreach (var group in groupedByDept)
{
Console.WriteLine($"Department: {group.Key}");
foreach (var emp in group)
Console.WriteLine($" - {emp.Name}");
}Use case: Generating department-wise reports, sales by category, etc.
5. Aggregating Data (Sum, Average, Min, Max, Count)
List<int> scores = new List<int> { 85, 92, 78, 90, 88 };
int total = scores.Sum();
double average = scores.Average();
int highest = scores.Max();
int lowest = scores.Min();
int count = scores.Count();
Console.WriteLine($"Total: {total}, Avg: {average}, Max: {highest}, Min: {lowest}, Count: {count}");Use case: Dashboards, analytics, and statistical summaries.
6. Joining Two Collections with Join
Combine data from two related sources — similar to a SQL join.
List<Customer> customers = new List<Customer>
{
new Customer { Id = 1, Name = "Emma" },
new Customer { Id = 2, Name = "Liam" }
};
List<Order> orders = new List<Order>
{
new Order { CustomerId = 1, Product = "Book" },
new Order { CustomerId = 2, Product = "Pen" },
new Order { CustomerId = 1, Product = "Laptop" }
};
var customerOrders = customers.Join(orders,
customer => customer.Id,
order => order.CustomerId,
(customer, order) => new { customer.Name, order.Product });
foreach (var item in customerOrders)
Console.WriteLine($"{item.Name} ordered {item.Product}");Use case: Relating customers with orders, students with courses, etc.
7. Checking Conditions with Any and All
List<int> ages = new List<int> { 22, 17, 30, 25 };
bool hasMinor = ages.Any(age => age < 18);
bool allAdults = ages.All(age => age >= 18);
Console.WriteLine($"Has minor: {hasMinor}"); // True
Console.WriteLine($"All adults: {allAdults}"); // FalseUse case: Validation logic — e.g., “Is any item out of stock?”
8. Removing Duplicates with Distinct
List<int> nums = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
var uniqueNums = nums.Distinct().ToList();
Console.WriteLine(string.Join(", ", uniqueNums));
// Output: 1, 2, 3, 4, 5Use case: Cleaning duplicate entries from imported or merged data.
9. Paging Data with Skip and Take
Essential for implementing pagination in APIs or UI grids.
List<string> items = Enumerable.Range(1, 50).Select(i => $"Item {i}").ToList();
int pageNumber = 2;
int pageSize = 10;
var page = items.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
Console.WriteLine(string.Join(", ", page));
// Output: Item 11, Item 12, ... Item 20Use case: Paginated API responses, table grids, infinite scroll.
10. Combining Multiple LINQ Operations (Method Chaining)
The real power of LINQ shows when you chain operations together.
List<Product> products = new List<Product>
{
new Product { Name = "Laptop", Price = 1200, Category = "Electronics" },
new Product { Name = "Shirt", Price = 40, Category = "Clothing" },
new Product { Name = "Phone", Price = 800, Category = "Electronics" },
new Product { Name = "Shoes", Price = 60, Category = "Clothing" }
};
var result = products
.Where(p => p.Category == "Electronics")
.OrderByDescending(p => p.Price)
.Select(p => new { p.Name, p.Price })
.ToList();
foreach (var item in result)
Console.WriteLine($"{item.Name}: ${item.Price}");
// Output:
// Laptop: $1200
// Phone: $800Use case: Building complex, readable queries — filter, sort, and shape data in a single fluent chain.
Why LINQ Matters
LINQ isn’t just syntactic sugar — it fundamentally changes how you think about data manipulation in C#. Benefits include:
- Readability — Queries read almost like plain English.
- Consistency — The same syntax works across lists, arrays, databases (via Entity Framework), and XML.
- Less Code — Replaces multi-line loops with single expressive statements.
- Type Safety — Compile-time checking catches errors early, unlike raw SQL strings.
Final Thoughts
LINQ is a must-know skill for any .NET developer. Once you get comfortable with Where, Select, GroupBy, Join, and method chaining, you'll find yourself writing cleaner, more maintainable code almost everywhere — from simple console apps to complex enterprise systems using Entity Framework.
Start small: pick one example above, try it in your own project, and build from there. Before long, LINQ will become second nature.









