linq
  1. linq-functional-concepts

Functional Concepts in LINQ

LINQ (Language Integrated Query) is a feature of C# that allows developers to write queries against different data sources like arrays, collections, databases, and XML files. LINQ is inspired by functional programming concepts like lambda expressions, lazy evaluation, and immutability.

In this article, we'll explore some functional programming concepts used in LINQ.

Lambda Expressions

A lambda expression is a short block of code that represents a method or function without a name. In functional programming, lambda expressions are used to pass behavior as an argument, much like a delegate in C#.

// Lambda expression to filter even numbers
var evenNumbers = numbers.Where(x => x % 2 == 0);

In the above code, we are passing a lambda expression as an argument to the Where() method to filter even numbers from the numbers collection.

Lazy Evaluation

Lazy evaluation is a technique used in functional programming to defer evaluation of expressions until they are actually needed. In LINQ, lazy evaluation means that when you write a LINQ query, the query is not executed immediately. Instead, the query is executed only when you iterate or enumerate the results using a foreach loop or other LINQ methods.

// query is not executed yet
var query = numbers.Where(x => x % 2 == 0);

// query is executed when we enumerate the results
foreach (var number in query)
{
    Console.WriteLine(number);
}

In the above code, the LINQ query is not executed until we enumerate the results using the foreach loop.

Immutability

Immutability is a core concept of functional programming, which means the state of an object cannot be modified after it is created. In LINQ, immutability means that when you write a LINQ query, the original data source is not modified. Instead, the query returns a new sequence of data that represents the result of the query.

// create a new sequence of even numbers
var evenNumbers = numbers.Where(x => x % 2 == 0);

// the original sequence of numbers is not modified
foreach (var number in numbers)
{
    Console.WriteLine(number);
}

In the above code, we are creating a new sequence of even numbers from the original sequence of numbers. The original sequence remains unchanged.

Summary

In this article, we explored some functional programming concepts used in LINQ. We've seen how lambda expressions are used to pass behavior as an argument, how lazy evaluation allows us to defer query execution until it is needed, and how immutability ensures that the original data source is not modified. By incorporating these functional programming concepts, LINQ provides a powerful querying mechanism that is concise, flexible, and composable.

Published on: