Linq and Fluent Programming

A LINQ Tutorial

I interviewed Bill Wagner for Yet Another Podcast while we were both at CodeMash fluent (look for his interview to be published next week).  In addition to being one of the nicest guys I know, he is also one of the smartest.

During the conversation he illustrated the ideas behind Linq and Fluent programming with a verbal example.  With his permission, I’ve picked up that example and present it here as a crisp crystallization of these key programming concepts.

To get started, let’s create a Windows Phone project, and on Main Page we’ll add three columns, each occupied by a ListBox control. Here’s the Xaml:

<!--ContentPanel -->
<Grid x:Name="ContentPanel"
       Width="1*" />
       Width="1*" />
       Width="1*" />
    Margin="5" />
    Margin="5" />
    Margin="5" />

We’ll fill the three list boxes with values in three different ways:

  • Imperative Programming
  • Query  syntax
  • Fluent syntax
    • Imperative Programming

    The imperative example is immediately understood by anyone who has been programming in C# for any length of time,

 private void CreateCollections()
    var someData = Enumerable.Range(1, 50);

    var inLoop = new List<int>();
    foreach(var n in someData)
          if (n > 5)
             inLoop.Add(n * n);
    LB1.ItemsSource = inLoop;

This is C# code that we live and breathe and it takes virtually no explanation. It feels natural, especially to those who have been doing imperative programming in one way or another since we were wee youngin’s.  (This is the essence of programming in BASIC, Pascal, C, C++, C#, etc. etc.)

Turning to Query Syntax using LINQ

The second example has become more common over the past few years and it is hard to escape the Query syntax in reading about Silverlight/ Phone/ C# programming. The syntax is very similar to SQL, except that the select statement is at the end.

var queryResult = from n in someData
                  where n > 5
                  select n * n;
LB2.ItemsSource = queryResult;

I read this as (roughly)  “for each value in someData, find all the values where the value is greater than 5 and then return the square of that number to queryResult, which will be a collection.”

A little odd, a little declarative, but if you’ve been working with SQL Server (and who hasn’t?) it isn’t brand new.

Fluency in Fluent Programming

Just when you thought it was safe to go back in the water, the folks who think a lot about programming idioms and patterns have begun to suggest that Fluent programming can make for more understandable (read: easier to maintain) programming.

The essence of fluent programming is that the output of one operation (or method) is the input to the next, creating a string of operations that together make for a very readable coding “sentence.”

In this case, we modify the Query statement using Lambda expressions,

var fluentResult = someData
      .Where(n => n > 5)
      .Select(n => n * n);
LB3.ItemsSource = fluentResult;

    Interpreting Lambda Expressions

There are two approaches to interpreting the lambda expression

Where(n=> n > 5)

One perfectly legitimate interpretation is to translate this in your mind to method syntax, where the value before the goes-to operator (=>) is the parameter, and the value to the right of the goes-to operator is the body of the method. This would amount to something like:

where ( IsGreaterThan5(n) )
private bool IsGreaterThan5(int n)
   return n > 5;

Another way to interpret this is simply as “return those values where the value is greater than 5”

In either case, the result of that filter is passed on to the statement to the right; that is only those values greater than five will be handed to the select.  It, in turn can be interpreted as “each value returns the square of that value.”

Thus, I read the entire statement as “assign to the collection fleuntResult the values that are found by starting with the collection someData and finding all the values where n is greater than five and then returning the square of those numbers.”

Thanks again to Bill Wagner who provided the code. Any mistakes in understanding or interpretation are my own.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Data, Essentials, Mini-Tutorial, Patterns & Skills, WindowsPhone and tagged . Bookmark the permalink.