O'Reilly logo

Functional Programming in C#: Classic Programming Techniques for Modern Projects by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

LINQ

LINQ is a functional API that is largely pure. It was introduced in .NET version 3.5, with Visual Studio 2008 and C# 3.0. Many of the new language features in C# 3.0 were originally introduced to support LINQ, and creative programmers have found many other applications since then. An in-depth look at LINQ is quite telling when trying to assess Microsoft’s position regarding functional programming in the “old” .NET languages (that is, leaving F# out of the equation).

LINQ to Objects

Many different features on both the language and the framework level play together for the experience provided by LINQ to Objects. The term LINQ to Objects usually describes the part of LINQ that works entirely within your application, that is, with native .NET objects as opposed to data that is queried from elsewhere. The latter scenario is also discussed later in this section, but for now the focus is what you can do with objects alone.

A very simple example of a LINQ query is this:

var values = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };

var valuesGreater5 =

  from v in values

  where v > 5

  select v;

Starting from a simple array of integer values, the query selects those values that are greater than 5. It’s important to understand that the query expression itself is just syntactic sugar, which is translated by the C# compiler into method calls. The API of LINQ is therefore language agnostic, and it could even be used from a .NET language that doesn’t have any special LINQ syntax. Here’s an equivalent ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required