LINQ & Lambda Expressions
Learn LINQ and lambda expressions for powerful data querying and manipulation. This is a foundational concept in Microsoft application framework that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET experience. Take your time with each section and practice the examples
What is LINQ?
Language Integrated Query (LINQ) provides a consistent way to query data from different sources. It allows you to write queries using C# syntax that work with collections, databases, and XML.. This is an essential concept that every .NET developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
LINQ Query Examples
// Sample data
List<Person> people = new List<Person>
{
new Person { Name = "John", Age = 25, City = "New York" },
new Person { Name = "Jane", Age = 30, City = "Los Angeles" },
new Person { Name = "Bob", Age = 35, City = "New York" },
new Person { Name = "Alice", Age = 28, City = "Chicago" }
};
// LINQ Query Syntax
var adultsInNY = from person in people
where person.Age >= 18 && person.City == "New York"
orderby person.Name
select person;
// LINQ Method Syntax
var adultsInNY2 = people
.Where(p => p.Age >= 18 && p.City == "New York")
.OrderBy(p => p.Name)
.ToList();
// Lambda expressions
var names = people.Select(p => p.Name).ToList();
var averageAge = people.Average(p => p.Age);
var groupedByCity = people.GroupBy(p => p.City);
// More complex queries
var result = people
.Where(p => p.Age > 25)
.GroupBy(p => p.City)
.Select(g => new { City = g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count)
.ToList();