Using LINQ in .NET Core for Data Queries


6 April 2018

Language-Integrated Query (LINQ) is one of the most powerful features of .NET, and it’s fully supported in .NET Core applications. It provides a simple, readable way to query and manipulate data directly within your code. Whether you’re working with in-memory collections, databases via Entity Framework Core, or XML data, LINQ makes querying data cleaner and more efficient.

In this post, we’ll dive into the basics of LINQ in .NET Core, exploring how it simplifies querying data and some of the most common LINQ operations, such as Where, Select, OrderBy, and GroupBy.


What is LINQ?

LINQ is a set of methods that enables you to perform data queries directly in C# using a syntax that’s integrated into the language itself. LINQ queries can be applied to different types of data sources, such as:

  • In-memory collections (e.g., arrays, lists)
  • Databases (via Entity Framework Core)
  • XML and JSON data
  • External data sources (e.g., REST APIs)

One of the major advantages of LINQ is that it allows you to query data using strongly typed C# code, making the queries type-safe, more readable, and easier to maintain.


Setting Up a Sample Project

Before we dive into LINQ operations, let’s set up a simple .NET Core Console Application to demonstrate some queries. You can use Visual Studio or Visual Studio Code for this:

  1. Create a new .NET Core Console Application: dotnet new console -n LINQExample cd LINQExample
  2. Create a simple data model: For this example, let’s say we have a list of people, and we want to query that list using LINQ. Here’s a basic Person class: public class Person { public string Name { get; set; } public int Age { get; set; } public string City { get; set; } }

Common LINQ Operations

Let’s now explore some of the most commonly used LINQ methods.


1. Where – Filtering Data

The Where method filters elements from a collection based on a condition. It returns all items that match the condition.

Example:

var people = new List<Person>
{
    new Person { Name = "Alice", Age = 30, City = "New York" },
    new Person { Name = "Bob", Age = 25, City = "Los Angeles" },
    new Person { Name = "Charlie", Age = 35, City = "Chicago" }
};

var filteredPeople = people.Where(p => p.Age > 30);

foreach (var person in filteredPeople)
{
    Console.WriteLine(person.Name);
}

Output:

Charlie

The Where method filters the list of people and returns only those with an Age greater than 30.


2. Select – Projecting Data

The Select method allows you to project each element of the collection into a new form. This is useful when you want to extract specific properties from the items in the collection.

Example:

var names = people.Select(p => p.Name);

foreach (var name in names)
{
    Console.WriteLine(name);
}

Output:

Alice
Bob
Charlie

In this example, Select returns a collection of just the Name properties of the people in the list.


3. OrderBy – Sorting Data

The OrderBy method is used to sort data based on a given key. By default, it sorts the data in ascending order. You can use OrderByDescending for descending order.

Example:

var orderedPeople = people.OrderBy(p => p.Age);

foreach (var person in orderedPeople)
{
    Console.WriteLine($"{person.Name} - {person.Age}");
}

Output:

Bob - 25
Alice - 30
Charlie - 35

The OrderBy method sorts the list of people by their Age in ascending order.


4. GroupBy – Grouping Data

The GroupBy method groups elements based on a key. It’s useful when you need to group similar data together and then perform operations on each group.

Example:

var groupedByCity = people.GroupBy(p => p.City);

foreach (var group in groupedByCity)
{
    Console.WriteLine($"City: {group.Key}");
    foreach (var person in group)
    {
        Console.WriteLine($"- {person.Name}");
    }
}

Output:

City: New York
- Alice
City: Los Angeles
- Bob
City: Chicago
- Charlie

In this example, the GroupBy method groups the people by their City. Each group contains a list of people who live in the same city.


Combining Multiple LINQ Operations

You can also combine multiple LINQ methods to perform more complex queries. For example, you can filter, sort, and then project the results.

Example:

var sortedAndFilteredPeople = people
    .Where(p => p.Age > 30)
    .OrderBy(p => p.Name)
    .Select(p => p.Name);

foreach (var person in sortedAndFilteredPeople)
{
    Console.WriteLine(person);
}

Output:

Charlie

Here, we first filter out people with an Age greater than 30, then sort them by name, and finally project only their names.


Conclusion

LINQ is a versatile and powerful feature in .NET Core that allows you to write elegant and efficient queries for data. Whether you’re dealing with in-memory collections, databases, or other data sources, LINQ simplifies data querying by providing a unified, easy-to-understand syntax.

In this post, we’ve covered some of the most common LINQ operations: Where, Select, OrderBy, and GroupBy. These operations form the foundation of most LINQ queries, and mastering them will significantly improve the way you interact with data in .NET Core applications.

In the next post, we’ll dive deeper into more advanced LINQ features, including Join, Distinct, and Aggregate, so stay tuned!

Happy coding!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *