
Member-only story
25 Advanced LINQ Queries Every .NET Developer Should Know
Are you looking to level up your LINQ skills? While you might be comfortable with basic LINQ operations, there’s a whole world of powerful queries that can make your code more elegant and efficient. In this article, we’ll break down 25 advanced LINQ queries in a way that’s easy to understand, with plenty of real-world examples.
You can also check my other article focused on the Advanced Concepts for JOIN in LINQ. 👇
1. Group-Join: Connecting Related Data
Think of Group-Join as a way to connect two lists where one item in the first list relates to multiple items in the second list — like finding all employees in each department.
// Let's say we have departments and employees
var departments = new List<Department>
{
new Department { Id = 1, Name = "IT" },
new Department { Id = 2, Name = "HR" }
};
var employees = new List<Employee>
{
new Employee { Name = "John", DepartmentId = 1 },
new Employee { Name = "Jane", DepartmentId = 1 },
new Employee { Name = "Bob", DepartmentId = 2 }
};
// GroupJoin combines them together
var departmentGroups = departments.GroupJoin(
employees,
dept => dept.Id,
emp => emp.DepartmentId,
(dept, emps) => new {
DepartmentName = dept.Name,
EmployeeCount = emps.Count(),
Employees = emps.Select(e => e.Name)
});
// Results:
// IT: 2 employees (John, Jane)
// HR: 1 employee (Bob)
Why is this useful? It’s perfect for scenarios like:
- Showing all departments, even those with no employees
- Creating reports that group data by department
- Building hierarchical data structures
2. Multiple Group-By: Organizing Data in Multiple Ways
Sometimes you need to group data by more than one thing at once. For example, grouping employees by both their department and location: