Tag Archives: Query

Fluent, Query & Imperative programming

 

Ways of programming.

In C#, there are several  ways of getting your program to work, even using a different syntax can make it seem as if two pieces of code are completely unrelated to each other if you don’t know how to read them.

I’m going to write code to find even numbers in a list in three different ways, and give an explanation of how I read them.

The first one is imperative. Anyone who has been programming in C# for a while should know this one, it’s probably how you and I started out. It’s straightforward code so not much explanation is required here.

  public void imperative(int[] n)

        {

            Console.WriteLine("Plain old imperative");

            for (var i = 0; i < n.Length; i++)

            {

                if(n[i] % 2 == 0)

                Console.WriteLine(n[i]);

            }

        }

This is trivial to understand, so let’s just skip ahead to the next way of writing this code.

        public void QuerySyntax(int[] n)

        {

            Console.WriteLine("With Query syntax");

            var x = from i in n

                    where i % 2 == 0

                    select i;

            foreach (var i in x)

            {

                Console.WriteLine(i);

            }

        }

This is the Query syntax language. People who are familiar with SQL will probably recognize some stuff, and immediately see that here it ends with the select instead of starting with it.

How I’d suggest reading it is like this: “Assign to variable (list) x, for every <element> in <collection> where <element % 2 == 0>, select that element and at it to x.” // if you read up to here, do you understand QuerySyntax?

Now you can’t just print x because it’s a collection, so we’ll have to do another loop to get the elements printed to the screen.

Once again, the foreach loop is something trivial to understand.

Our last stop is the Fluent way of writing this code, very similar to the query syntax but with a Lamda expression.

   public void Fluent(int[] n)

        {

            Console.WriteLine("Fluent");

            var x = n

                .Where(i => i % 2 == 0)

                .Select(i => i);

            foreach (var i in x)

                Console.WriteLine(i);

        }

Well, what might make you frown upon this at first is the Lamda syntax that is used. Maybe you’re familiar with this, though it seems to be less common than the other two.

I’ll try to explain this to you once again like how I would read it.

“Assign a variable to n. For every element where ((input % 2 ==0)) . Select that element and add this one to the list n”

Next stop is our foreach loop, once again a trivial thing to understand even when the brackets are missing.

When we run these methods one after another this is what we get.