C# Workshop – Lambdas & LINQ

Standard

Lambdas & LINQ

C# has a special type of Method that can be used as an alternative to creating another named Method you use but are created in-line with your code, they can be passed as a Parameter to other methods and these are known as Lambda expressions.

To use a Lambda expression in C#, in dotnetfiddle.net enter the following:

using System;

public class Demo
{
	public static void Main()
	{
		Func<int, int> addTen = x => x + 10;
    		Console.WriteLine(addTen(4));
	}
}

In the example, there is a Func which is a variable the Lambda is assigned to then to the right of the = is the Lambda expression and there is two parts, the first is the Parameter passed in and then there is a special operator => pronounced as “produces” which is followed by the code to execute and can be done in one line and doesn’t require a return statement like a Method that returns a value would normally need.

To use multiple Parameters with a Lambda in dotnetfiddle.net by entering the following:

using System;

public class Demo
{
	public static void Main()
	{
		Func<int, int, int> area = (x,y) => x * y;
    		Console.WriteLine(area(4,5));
	}
}

Lambda expressions are a powerful and easy way to access functionality without needing a separate Method and can be reused in many places just like a Method but also passed into a Method like a Value can be.

The language of C# is powerful but to add to this power is a way of querying sets and lists of data using LINQ or Language-Integrated Query, which is a set of Extension Methods which are a special kind of static Method to extend existing types with new functionality and in LINQ this is used extensively and makes performing what would be complex tasks much easier and just requires the inclusion of another using for System.Linq and they also make use of Lambda expressions.

The following examples will add to the previous, so to start will need a class and then a collection of them as a List by entering in to dotnetfiddle.net the following:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Workshop
{
	public class Person
	{		
		public string Forename { get; set; }
		public string Surname { get; set; }
		public int Age { get; set; }
	}	
	
	public class Demo
	{
		public static void Main()
		{
			List<Person> people = new List<Person>();
			people.Add(new Person { Forename = "John",
 			Surname = "Smith", Age = 30 });
			people.Add(new Person { Forename = "Jane",
 			Surname = "Smith", Age = 42 });
			people.Add(new Person { Forename = "John",
 			Surname = "Doe", Age = 24 });
			people.Add(new Person { Forename = "Jane",
 			Surname = "Doe", Age = 58 });
		}
	}
}

In this example, there is a class of type of Person which has two Properties of string and another of int then there is a List of Person which is then added to or populated with some values and this example will be added to in subsequent examples.

LINQ allows you to search for items within a collection that match a set of criteria and is the main component of Language-integrated Query, which is to Query data, which can be done with where.

To use where with LINQ in dotnetfiddle.net, add into Main at the end the following:

IEnumerable<Person> overFourty = people.Where(x => x.Age > 40);
Console.WriteLine(overFourty.Count());

In this part of the example there is the use of IEnumerable<Person> which is the type of item that. The where uses a Lambda and the expression looks for any item that is in the List which has an Age value greater than 40 and then outputs this value which should be 2 using another LINQ method of count.
You may have too many items in the collection or not have enough properties and you can use the select Method in LINQ which can be a useful way of converting an existing Collection into other collections or values.

To use select with LINQ in dotnetfiddle.net, add below last example the following:

IEnumerable<string> foreNames = people.Select(x => x.Forename);
foreach(string foreName in foreNames)
{
	Console.WriteLine(foreName);
}

In this part of the example the select is used to get the Forename for each Person in the Collection and will return a collection of string Objects that are then looped though with a foreach statement to output each Forename.
You may just want to get one item from a collection and you can do this in LINQ with First, Last and Single to get an item or FirstOrDefault, LastOrDefault and SingleOrDefault where …OrDefault is the default value for a type which is usually null in case the value being looked for in the collection is not present.

To use first & last with LINQ in dotnetfiddle.net, add below last example the following:

Person first = people.First();
Person last = people.Last();
Console.WriteLine(first.Surname);
Console.WriteLine(last.Surname);

It is also possible to get information about a collection using LINQ with count, any and allcount was used previously and will return the number of items in the collection but it can also take a Lambda expression or Predicate like a where does so you could count only certain things that match the expression. With any this will check the collection and see if anything that matches the Predicate expression matches and will return true if it does, and false if not and all which is like any except that all values must match to return true otherwise it will return false.

To use count in dotnetfiddle.net, add below the last example the following:

Console.WriteLine(people.Count(x => x.Age < 50));

To use any in dotnetfiddle.net, add below the last example the following:

Console.WriteLine(people.Any(x => x.Surname == "Doe"));

To use all in dotnetfiddle.net, add below the last example the following:

Console.WriteLine(people.All(x => x.Forename == "John"));

The results of many of the LINQ queries shown have been of IEnumerable of a type such as int or string, but there may be times where you need a different type than IEnumerable and LINQ has Extension Methods that allow you to do this.

To get a List of the type returned by LINQ in dotnetfiddle.net, enter the following:

List<string> list = people.Select(x => x.Forename).ToList();

To get an Array of the type returned by LINQ in dotnetfiddle.net, enter the following:

string[] array = people.Select(x => x.Forename).ToArray();

LINQ is a very powerful addition to C# and there are many more ways you can use it to get various parts of a collection, think of it as a search engine for your code, whatever information is in there, you can get at it with LINQ expressions and can use them in combination with each other to make your applications much more powerful than they would otherwise be and makes it easy and straightforward to manipulate data.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s