Basics: Lambda Linq

Introduction

As there are many introductions out there that explain what LINQ and lambdas are, I’m not going to delve to deeply into that subject. Essentially, they are quick hand ways of writing instructions on lists. The most common of those instruction are filtering, selecting and ordering.

This tutorial has been written with a combination of LINQ and lambda. The LINQ is structured closer to that of SQL, but using lambda we get an even more streamlined language to work with.

I will be dealing with IEnumerable’s in this tutorial, but you can use those commands on most Arrays / Lists. Once a command has been returned though it will be as a IEnumerable.

Example – Filtering

We have a list of numbers and we only want the ones which are greater than 5.

Filtering – Without LINQ / Lambda

 private static void Main()

        {

            IEnumerable<int> numbers = new[] {9, 3, 7, 4, 8, 1, 1, 5};

            numbers = GreaterThanFive(numbers);

        }

 

        private static IEnumerable<int> GreaterThanFive(IEnumerable<int> numbers)

        {

            foreach (var number in numbers)

            {

                if (number > 5) yield return number;

            }

        }

Filtering – With LINQ / Lambda

                 private static void Main(string[] args)

        {

            IEnumerable<int> numbers = new[] {9, 3, 7, 4, 8, 1, 1, 5};

 

            numbers = numbers.Where(number => number > 5);

        }

Looking at the non LINQ
/ Lambda compared to the one which uses LINQ / Lambda, you can instantly see there are less lines to the code. Now having less lines and being more compressed means nothing if you lose the readability but have a look, it’s actually more readable!

As this is the first of the tutorial I will run through the structure next of a LINQ / Lambda statement

Structure

Explaining the structure of LINQ / Lambda is where I found that most people explained them poorly.

Let use the Linq / Lambda from
Example 1: numbers.Where(number => number > 5)

Key Description
 numbers Is the list of items we will be using
 Where States we want to filter out items from the list which are false in the statement. Which in our case is “number > 5”
number The first appearance of the word “number” is for stating what each item should be named when working on it. It is exactly the same as doing a foreach loop:”var number in numbers

The list doesn’t need to be supplied as the Where method is called from the list.

 Numbers Is the list of items we will be using
 Numbers Is the list of items we will be using

I’m going explain the naming of each item a little further: “number => number > 5”

You must understand that the name can be anything! This is the part that scrambled my brain for so long and there is a reason why it scrambled my brain for so long. You’ll find that most people will constantly use the letter ‘o’ as the name. So when I first came across it you could be reading a list of numbers / letters / words and trying to filter, but everyone would have something like the following in their
tutorials:

words.Where(o => o.StartsWith(“L”))

numbers.Where(o => o % 2)

Now personally I think while your learning, you should stick with full names like I have in the example. Once you are comfortable you should
move to single character names (you don’t have to). Even then it’ll be beneficial to use a letter which correlates to the what the item is (you can nest LINQ / Lambda statements, when dealing with multi-dimensional arrays or classes within classes and getting used to have unique names means your less likely to run into naming conflicts).

Ordering

The example covered how to filtering, now we are going to deal with ordering. There is a reason why I’m dealing with them in this order and that is that I personally filtering easier than ordering and ordering easier than selecting to explain and understand.

If you’ve run the code from example 1 you’ll notice the numbers are output in the following order: 9, 7, 8

Ordering is a very simple process and very similar to the “Where” method.

Ordering in ascending order:

numbers.OrderBy(number => number)

Ordering in descending order:

numbers.OrderByDescending(number => number)

If we were dealing with classes we’d select a property on the second “number”.

The are another two features of LINQ / Lambda that it’s about time I brought up. The first of those features is chaining and what this means is that instead of having to have:

numbers = numbers.Where(o => o > 5);

numbers = numbers.OrderBy(o => o);

We can put them as a single line:

numbers = numbers.Where(o => o > 5).OrderBy(o => o);

We are allowed to do this because LINQ / Lambda commands returns a list of type IEnumerable<T> (in this case it’s a IEnumerable<int> list).

Now for the other piece of information, which is related to the ordering. When you have multiple properties, you may wish to order by one property and then another. In those cases you use the “ThenBy” or “ThenByDescending” method and not by calling the “OrderBy” or “OrderByDescending” method.

Selecting

Select allows you to either only select specific properties of the list of objects you have, or return something with a calculation done to it. First I’ll show you an example dealing with the numbers list and then I’ll show you another example, the second being a little more difficult than the first.

For this example, we are going to multiple each number in the numbers variable by 5. The result will be that we’ll have a list of the results.

IEnumerable<int> numbers = new[] {9, 3, 7, 4, 8, 1, 1, 5};

numbers = numbers.Select(number => number * 5); // Results: 45, 15, 35, 20, 40, 5, 5, 25

The next example will be a list of cars and the select statement will return a list of their names only.

 private class Car

        {

            public string Name { get; set; }

            public int ReleaseYear { getset; }

            public int CostInDollars { getset; }

        }

        private static void Main(string[] args)

        {

        IEnumerable<Car> cars = new[]

            {

                new Car { CostInDollars = 120000, Name = “Wonky Wagon”, ReleaseYear = 1973 },

                new Car { CostInDollars = 90000, Name = “Comfy Steel”, ReleaseYear = 1998 },

                new Car { CostInDollars = 300000, Name = “Compensating Car”, ReleaseYear = 2018 }

            };

            var carNames = cars.Select(car => car.Name);

        }

The first thing you should note is that I haven’t a clue about cars 😊. The second is that this time, we’ve had to
create a new list container for the results. This is because what we’ve selected isn’t of the same type of list. Our first select, simply got each
number and timed it by 5. So we where running the query using a list of numbers and returning a list of numbers. Here we are using a list of cars and returning a list of strings / names. You could create a new object of car in the “Select” and return them and then you’d be able to
use the same container… but that’s a little past the point of this tutorial.

The rest is pretty easy to understand. We are select the name of each object in the cars list.

There are many more methods for LINQ / Lambda out there and if your interested I’d fully recommend learning the other methods. Hopefully this tutorial has given you the understanding of how to use them. I use the following site as a reference, as it has clean and
relatively easier following examples: http://linqsamples.com/