Skip to main content

Using LINQ with Collections

Introduction

In this tutorial, we are going to explore how to use Language Integrated Query (LINQ) with collections in C#. LINQ is a powerful feature in C# that allows us to query data from different data sources (like collections, XML, databases) in a consistent, easy to understand manner.

What is LINQ?

LINQ is a set of features introduced in .NET Framework 3.5 that provides a rich, standardized way to query and manipulate data. It integrates querying capabilities directly into C# language, and can be used with any data source, not just databases.

What is a Collection?

In C#, a collection is a group of objects. These objects can be of different types. The .NET Framework provides several classes that can be used to work with collections, including the List, Dictionary, HashSet, and Queue classes, among others.

Using LINQ with Collections

Now, we are going to see how to use LINQ with collections.

Basic LINQ Query

Let's start with a basic LINQ query that retrieves all even numbers from a collection. Here is how you can do it:

List<int> numbers = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

var evenNumbers = from num in numbers
where num % 2 == 0
select num;

foreach (int num in evenNumbers)
{
Console.WriteLine(num);
}

In the above example, we first create a list of integers. Then, we use a LINQ query to retrieve all even numbers from the list. The where keyword is used to filter the numbers, and the select keyword is used to specify what we want to retrieve.

Ordering

LINQ also provides a way to order the data in collections. For instance, you can sort the numbers in a list in ascending or descending order like this:

var orderedNumbers = from num in numbers
orderby num
select num;

foreach (int num in orderedNumbers)
{
Console.WriteLine(num);
}

In the above example, the orderby keyword is used to sort the numbers in ascending order.

Grouping

With LINQ, you can also group data in collections. Let's say you have a list of strings and you want to group them by their first letter:

List<string> words = new List<string> {"apple", "banana", "berry", "cherry", "mango", "melon", "orange"};

var groupedWords = from word in words
group word by word[0];

foreach (var group in groupedWords)
{
Console.WriteLine("Words that start with the letter " + group.Key + ":");

foreach (var word in group)
{
Console.WriteLine(word);
}
}

In the above example, the group keyword is used to group the words by their first letter.

Conclusion

In this tutorial, we have covered the basics of using LINQ with collections in C#. We have seen how to create a basic LINQ query, how to order and group data in collections. As you can see, LINQ provides a powerful and easy-to-use way to query and manipulate data in collections. With practice, you will be able to use LINQ to perform more complex queries and operations on collections.