LINQ is a powerful feature in C# that allows you to query and manipulate data in a declarative and SQL-like syntax. LINQ to Objects specifically enables you to query in-memory collections like arrays, lists, and other IEnumerable<T> types.
Let's create a simple console application to demonstrate LINQ to Objects with step-by-step explanations.
Step 1: Create a new Console Application
Open Visual Studio and create a new Console Application. Name it as you wish.
Step 2: Define a Sample Data Collection
For this tutorial, let's create a simple class and a collection of objects:
Step 3: Basic LINQ Queries
Now, let's start with some basic LINQ queries.
Filtering
var adults = from person in peoplewhere person.Age >= 18select person;foreach (var adult in adults){Console.WriteLine($"{adult.Name} is an adult.");}
Projection
var namesOnly = from person in peopleselect person.Name;foreach (var name in namesOnly){Console.WriteLine($"Name: {name}");}
Step 4: Ordering and Aggregation
Ordering
var orderedByAge = from person in peopleorderby person.Ageselect person;foreach (var person in orderedByAge){Console.WriteLine($"{person.Name} - {person.Age} years old");}
Aggregation
int averageAge = people.Average(person => person.Age);Console.WriteLine($"Average Age: {averageAge}");
Step 5: Advanced LINQ Queries
Grouping
var groupedByAge = from person in peoplegroup person by person.Age;foreach (var group in groupedByAge){Console.WriteLine($"People aged {group.Key}:");foreach (var person in group){Console.WriteLine($" {person.Name}");}}
Joining
var departments = new List<string> { "HR", "IT", "Finance", "Marketing" };var peopleWithDepartments = from person in peoplejoin department in departmentson person.Age % departments.Countequals departments.IndexOf(department)select new { person.Name, Department = department };foreach (var person in peopleWithDepartments){Console.WriteLine($"{person.Name} works in {person.Department} department.");}
Conclusion
This tutorial covers the basics of LINQ to Objects in C#. You can explore more advanced features and operations, such as Skip
, Take
, Any
, All
, etc., to further enhance your querying capabilities. LINQ is a versatile tool that can greatly simplify data manipulation in your C# applications.