LINQ queries and lambda expressions in C#

Lesson 11 of 15 · C#

LINQ (Language Integrated Query) is a powerful tool in the .NET framework that lets you query and manipulate data from different sources using the same query language, directly inside C# (or other .NET languages). LINQ simplifies working with data, whether the data is in memory, in a database, in XML documents or somewhere else.

Key features of LINQ

  • A single query language: LINQ lets you query different kinds of data sources (in-memory collections, databases, XML, etc.) with one syntactic style, which simplifies working with data.
  • Integration with languages: LINQ is integrated into the programming language, which means that queries and data manipulation can be written directly in C# or VB.NET code, not as separate SQL queries or other specific languages.
  • Object-oriented: LINQ lets you query objects and in-memory collections through the methods and properties of classes, which avoids the need to write low-level loops for searching and filtering.
  • Static type checking: LINQ uses static type checking, which helps detect errors at compile time rather than at run time.

Basic components of LINQ

  • LINQ to Objects: Queries over collections of objects in memory, such as lists or arrays. This makes it possible to filter, sort and group data directly in the code.
  • LINQ to SQL: Lets you query SQL databases with a SQL-like syntax integrated into C# code.
  • LINQ to Entities: Uses Entity Framework to query data in a database, making it possible to work with relations and data through objects.
  • LINQ to XML: Lets you work with XML data using LINQ queries for filtering and manipulating XML documents.

LINQ query examples

1. LINQ to Objects (in memory)

using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
    public static void Main()
    {
        // A list of passengers
        List<Passenger> passengers = new List<Passenger> {
            new Passenger("Anna", "Peterson", "online"),
            new Passenger("Mark", "Johnson", "counter"),
            new Passenger("Ivy", "Nicholson", "online"),
            new Passenger("Peter", "Smith", "online")
        };

        // A LINQ query for filtering and sorting
        var onlinePassengers = passengers
                                .Where(p => p.PurchaseMethod == "online" && p.Reservation)
                                .OrderByDescending(p => p.FirstName);

        // Printing the results
        foreach (var p in onlinePassengers)
        {
            Console.WriteLine(p.ToString());
        }
    }
}

Description:

This code shows a simple example of using LINQ (Language Integrated Query) in C#. The goal of the code is to filter and sort a list of passengers according to certain criteria.

First, a class is created that describes an object representing a passenger on a train.

public class Passenger
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PurchaseMethod { get; set; }
    public bool Reservation { get; set; }

    public Passenger(string firstName, string lastName, string purchaseMethod)
    {
        FirstName = firstName;
        LastName = lastName;
        PurchaseMethod = purchaseMethod;
        Reservation = true; // Let us assume that all passengers have made a reservation
    }

    public override string ToString()
    {
        return $"{FirstName} {LastName}, {PurchaseMethod}";
    }
}

This Passenger class has four properties:

  • FirstName (string): The passenger's first name.
  • LastName (string): The passenger's last name.
  • PurchaseMethod (string): How the passenger bought the ticket (for example "online" or "counter").
  • Reservation (bool): Whether the passenger has made a reservation (in this example we assume that everyone has a reservation).

After that, the list of passengers is defined and filled.

This list "passengers" contains four objects of type Passenger, each with a different first name, last name and purchase method.

A LINQ query for filtering and sorting

  • Where: This method filters the list of passengers and returns only those who bought their ticket "online" and have made a reservation (Reservation == true).
  • OrderByDescending: This method sorts the results by the passenger's first name, in descending order (from Z to A).

Finally, there is a foreach loop that goes through the list of passengers, one in each pass. This part of the code goes through all the filtered and sorted passengers and prints their data (first name, last name and purchase method).

Program output:

Peter Smith, online
Ivy Nicholson, online
Anna Peterson, online

This example shows how you can use LINQ to filter and sort a collection of objects in C#. Specifically, the passengers who bought their ticket online are picked out of the list and sorted by first name in descending order.

LINQ to SQL (in a database)

using System;
using System.Linq;
using System.Data.Linq;

public class Program
{
    public static void Main()
    {
        using (var context = new MyDataContext())
        {
            var passengers = from p in context.Passengers
                             where p.PurchaseMethod == "online" select p;

            foreach (var p in passengers)
            {
                Console.WriteLine($"{p.FirstName} {p.LastName}");
            }
        }
    }
}

Explanation of the example

using System;
using System.Linq;
using System.Data.Linq;
  • using System;: Imports the basic classes and types needed to work with the .NET framework, including classes for working with the console, data types, etc.
  • using System.Linq;: Imports the LINQ (Language Integrated Query) libraries that make it possible to use queries inside C# code to work with collections of data.
  • using System.Data.Linq;: Imports the LINQ to SQL libraries that map relational databases to .NET objects, making it easier to work with data from databases using an object-oriented approach.

Defining the Program class and the main method Main

public class Program
{
    public static void Main()
    {
        // Code inside the method
    }
}
  • public class Program: Defines a public class called Program that contains the main method of the program.
  • public static void Main(): The main entry point of the program. When the program starts, execution begins with this method.

Creating and using a DataContext

using (var context = new MyDataContext())
{
    // Operations on the database
}
  • using: The using block makes sure that resources are released properly once you are done with them. In this case, it makes sure that the database connection is closed after the operations are executed.
  • var context = new MyDataContext():
    • MyDataContext: This is the class that represents the database context. It is usually generated with a tool such as the LINQ to SQL Designer or defined by hand. It contains mappings of the database tables to C# classes.
    • Creating an instance of the MyDataContext class establishes a connection to the database and makes it possible to interact with its tables.

Note: The MyDataContext class must be defined beforehand and configured with a correct connection string that connects to the appropriate database.

Defining a LINQ query

var passengers = from p in context.Passengers
    where p.PurchaseMethod == "online" select p;

This piece of code defines a LINQ query that:

  • from p in context.Passengers:
    • Accesses the Passengers table in the database through the context.
    • Each record from the Passengers table is represented by the variable p.
  • where p.PurchaseMethod == "online":
    • Filters the records so that only those where the value of the PurchaseMethod column equals "online" are kept.
  • select p;:
    • Selects the filtered records and forms a collection of results stored in the variable passengers.

Important: This query uses deferred execution, which means that it is not executed immediately when it is defined, but only when you iterate through the results or call a method that forces execution (for example ToList()).

Executing the query and printing the results

foreach (var p in passengers)
{
    Console.WriteLine($"{p.FirstName} {p.LastName}");
}
  • foreach (var p in passengers):
    • Iterates through every result obtained from the previous LINQ query.
    • At this point the query is actually executed against the database, and the results are returned to the application.
  • Console.WriteLine($"{p.FirstName} {p.LastName}");:
    • Prints the first and last name of every passenger who bought a ticket online.
    • String interpolation is used to format the output.

The complete code with extra explanations

using System;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;

// Defining the Passenger entity
[Table(Name = "Passengers")]
public class Passenger
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int Id { get; set; }

    [Column]
    public string FirstName { get; set; }

    [Column]
    public string LastName { get; set; }

    [Column]
    public string PurchaseMethod { get; set; }
}

// Defining the DataContext
public class MyDataContext : DataContext
{
    public Table<Passenger> Passengers;

    public MyDataContext()
        : base("YourConnectionStringHere")
    {
    }
}

public class Program
{
    public static void Main()
    {
        using (var context = new MyDataContext())
        {
            var passengers = from p in context.Passengers
                             where p.PurchaseMethod == "online" select p;

            foreach (var p in passengers)
            {
                Console.WriteLine($"{p.FirstName} {p.LastName}");
            }
        }
    }
}
  • The Passenger class:
    • Marked with the [Table] and [Column] attributes, which map the class and its properties to the corresponding table and columns in the database.
  • The MyDataContext class:
    • Inherits from the DataContext class and contains a Table<Passenger>, which makes it possible to query the Passengers table.
    • A connection string that defines the connection to the database is passed to the constructor.

This example demonstrates how to use LINQ to SQL to access and manipulate data from a relational database simply and efficiently, using C# and an object-oriented approach. LINQ to SQL lets you write queries in an intuitive way, using the syntax of the C# language, without having to write raw SQL queries.

Advantages of using LINQ to SQL:

  • Typed queries: Errors are detected at compile time.
  • Easier code maintenance: Queries are more readable and easier to understand.
  • Integration with the C# language: You use familiar syntax and language concepts.
  • Security: Less chance of SQL injection, because the queries are generated automatically.

Note: LINQ to SQL is suitable for small and medium-sized applications. For more complex scenarios and databases, an ORM tool such as Entity Framework, which offers more capabilities and flexibility, is recommended.

Components of a LINQ query

  • Data source: A collection of objects, a table in a database or an XML document.
  • Query operator: A function such as Where, Select, OrderBy, GroupBy, etc., which defines what you want to do with the data.
  • Execution: The query is executed when the data is actually requested, which allows deferred execution and optimization.

Conclusion

LINQ makes working with data easier, makes code more readable and lets you work with different kinds of data using the same syntax. It provides an elegant way to filter, sort and manipulate data in .NET applications.

Lambda expressions

Lambda expressions are a key part of modern programming languages such as C#, and they let you write inline, anonymous functions. In essence, lambda expressions make it possible to define methods without having to create separate methods or classes.

Key features of lambda expressions

  • Anonymous methods: Lambda expressions are anonymous, which means that they do not have a name like classic methods. Instead, they are used in a context where a delegate or a function such as Func<T>, Action<T> or Predicate<T> can be used.
  • Short syntax: Lambda expressions provide a shorter and more readable syntax for writing small functions, especially when they are used in LINQ queries or in functional programming styles.
  • The closure concept: Lambda expressions can "capture" variables from the surrounding scope, which gives access to local variables from a function that is executed later.

Lambda expression syntax

Lambda expressions use the => operator, which is called the "lambda operator". The syntax is as follows:

(parameters) => expression

Or for more complex expressions:

(parameters) =>
{ statement1; statement2; }

Lambda expression examples

1. A simple lambda expression

// Defines a lambda expression that adds 10 to the given number
Func<int, int> addTen = x => x + 10;

int result = addTen(5); // result = 15

2. A lambda expression in a LINQ query

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Uses a lambda expression to filter the numbers greater than 3
        var filteredNumbers = numbers.Where(n => n > 3);

        foreach (var number in filteredNumbers)
        {
            Console.WriteLine(number); // Prints 4 and 5
        }
    }
}

This code demonstrates how to use a lambda expression together with the LINQ method Where to filter the elements of a list that satisfy a certain condition. Specifically, in this example the numbers greater than 3 are filtered.

Here, further:

  • A generic list of integers (int) is defined.
  • new List<int> { 1, 2, 3, 4, 5 };: Initializes the list with the numbers 1, 2, 3, 4 and 5.

Next comes the lambda expression

var filteredNumbers = numbers.Where(n => n > 3);

numbers.Where(n => n > 3):

  • Where: This is a LINQ method used to filter the elements of a collection according to a certain condition.
  • n => n > 3: This is a lambda expression that represents the filtering condition.
    • n: Represents each individual element of the list numbers.
    • n > 3: The condition that filters the numbers; it returns true only for the numbers greater than 3.
  • The Where method returns a collection that contains all the elements of the original list that satisfy this condition. In this case, these are the numbers 4 and 5.
  • var filteredNumbers:
    • The variable filteredNumbers stores the result of this filtering, which is the list of numbers greater than 3.

3. A lambda expression with several parameters

// A lambda expression for adding two numbers
Func<int, int, int> add = (a, b) => a + b;

int sum = add(3, 4); // sum = 7
  • Func<int, int, int>: Func is a generic delegate in C# that can accept up to 16 parameters and returns a value. In this case, Func<int, int, int> defines a delegate that takes two int parameters and returns an int value.
  • The lambda expression: (a, b) => a + b is a lambda expression that represents an anonymous function. It takes two arguments (a and b) and returns the result of adding them (a + b).
  • add: The lambda expression is assigned to the variable add, which is of type Func<int, int, int>. This means that add can be used as a function that takes two int arguments and returns their sum.
  • Calling the function: int sum = add(3, 4); calls the function add with the arguments 3 and 4. The result of the addition (which is 7) is stored in the variable sum.

This approach is flexible and lets you define functions on the fly, without having to write methods explicitly.

Using lambda expressions

  • Filtering data: Lambda expressions are often used to filter data in LINQ queries, as shown in the previous examples.
  • Sorting data: Lambda expressions can be used to sort collections of data, for example to sort a list by a certain criterion.
  • Defining delegates: Lambda expressions can be used to assign methods directly to delegates, which makes simple functionality in code possible.

Conclusion

Lambda expressions are a powerful tool in C# that lets you write compact and readable functions. They are especially useful for working with collections and for a functional programming style, as well as for creating inline methods without having to create separate methods.

Check your knowledge

Open the quiz

LINQ and lambda expressions

1. What is the lambda expression x => x * 2?




2. Which LINQ method picks out the elements that satisfy a condition?




3. Which LINQ method turns each element into something else?




4. Which namespace must be included for LINQ?