DEV Community

Cover image for C# - Functional Programming with LINQ
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Functional Programming with LINQ

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. While C# is primarily an object-oriented language, you can apply functional programming concepts, such as immutability and pure functions, using LINQ and custom extension methods.

Here's an example of using functional programming concepts to transform a list of numbers:

using System.Data;

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

        // Using LINQ and functional-style operations to transform the list
        var result = numbers
            .Where(n => n % 2 == 0)  // Filter even numbers
            .Select(n => n * 2)      // Double each number
            .ToList();

        Console.WriteLine(string.Join(", ", result)); // Output: 4, 8
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We use Where to filter even numbers.
  • We use Select to double each number.
  • The result is collected into a new list.

By chaining these LINQ methods, you can apply transformations to collections in a functional and declarative way, avoiding explicit loops and mutable variables. This approach can make your code more readable and maintainable.

While C# is primarily an object-oriented language, you can apply functional programming principles to specific parts of your code where it makes sense, such as data transformations using LINQ, to improve code clarity and maintainability.

Top comments (0)