DEV Community

Cover image for C# Lambda Expressions & Lambda Operator
Grant Riordan
Grant Riordan

Posted on

C# Lambda Expressions & Lambda Operator

As you progress through C# you'll see lambda expressions used more and more, and you'll begin using them yourself a lot more, due to their ease of use and keeping your code concise.

What does lambda expression do?

Lambda expressions are simply anonymous methods declared using the lambda operator =>. They have parameters and and method declaration or return declaration. We seperate the parameters from the body of the function using the => operator.

Many LINQ methods (upcoming topic on my blog), take an expression as a parameter, and we can provide this in the form of a lambda expression (examples coming up).

How to declare a lambda expression ?

They can be declared in two ways ,both do exactly the same thing, it all depends on what you'd like to do within the function.

Option 1:



(paramA, paramB) => expression

//or with single paramater we don't need to use brackets
paramA => expression

//Example
var list = new List<Animal>() {
        new Animal() {Name="Dog", Age = 1, NumberOfLegs = 4, Sound = "Bark" },
        new Animal() {Name="Cat", Age = 2, NumberOfLegs = 4, Sound = "Meow" },
        new Animal() {Name="Duck", Age= 1, NumberOfLegs = 2, Sound = "Quack"}
};

var dog = list.Where(x => x.Name == "Dog");



Enter fullscreen mode Exit fullscreen mode

Here we're using a lambda expression within the Where() method, to retrieve the Dog object.

Let's break it down:

Lambda expression example breakdown

Parameter A - Notice that the parameter doesn't explicitly specify a data type. The compiler always infers the data type of lambda expression parameters from their context, in this case it'll be a string as the context is from the List;

Then the expression is comparing the Name property of the item in the list, to a string of "Dog".
The Where() method is using that lambda, to then query the list for any matching items.
The Where() method will then return all the items in the list that match the criteria declared in the expression.

So if we were to add another Dog into the mix, say an unfortunate 3 legged dog, and queried it we'd get 2 (two) results.



var list = new List<Animal>() {
    new Animal() {Name="Cat", Age = 2, NumberOfLegs = 4, Sound = "Meow" },
    new Animal() {Name="Dog", Age = 2, NumberOfLegs = 3, Sound = "Meow" },
    new Animal() {Name="Dog", Age = 1, NumberOfLegs = 4, Sound = "Bark" },
    new Animal() {Name="Duck", Age= 1, NumberOfLegs = 2, Sound = "Quack"}
};

var dogs = list.Where(x => x.Name == "Dog").ToList();
var count = dogs.Count();

//Output =  2;


Enter fullscreen mode Exit fullscreen mode

Option 2

You can also use a lambda expression to complete more complex functions, using the "{ }" syntax we see in class methods. For example we can write a lambda function within the ForEach() method on a list like so:




var list  = new List<string>(){
    "Grant", "Alice", "Bono"
};

list.ForEach(x=> {
    var greeting = $"Hello {x} - Welcome to the Team";
    Console.WriteLine(greeting);
})

//Output
// Hello Grant - Welcome to the Team
// Hello Alice - Welcome to the Team
// Hello Bono - Welcome to the Team


Enter fullscreen mode Exit fullscreen mode

The Difference here is the function isn't just doing one thing, or simply returning something, so we need to wrap the body of the function within "{}" to illustrate it's a more complex multi-line function.

Code Examples:

Declaring functions



Func<int, int, int> Multiply = (x,y) => x*y;
int result = Mutliply(3,5); // 15


Enter fullscreen mode Exit fullscreen mode

Simple multiplication function that takes in two numbers and multiplys them to return another int.
Func states that we're going to pass it two ints, and it's going to return an int too.

It follows the following formula Func<in, out> or Func<in,in,in,out> the out is always the last specified type.

For example if we wanted it to take two integers, but return as a string we'd declare like this



Func<int,int,string> Multiply = (x,y) => (x*y).ToString();


Enter fullscreen mode Exit fullscreen mode

Single line declarations don't require the return keyword, it's done implicitly, however multiline functions would, for example:



Func<string, string> GetGreeting = (name) => {
    var timeOfDay = DateTime.Now.Hour < 12 ? "Good Morning" : "Good Afternoon";
    var message = DateTime.Now.Hour < 17 ? "Have a great evening" : "Enjoy the rest of your day";
    return $"{timeOfDay} - {name} -- {message}";
};
Console.WriteLine(GetGreeting("Grant"));   


Enter fullscreen mode Exit fullscreen mode

Return properties

Here we have no parameters, but we're not declaring a function either, we're using the lambda expression to declare a return value for a readonly property within a class.




public string DisplayName => $"Welcome {this.Name} - Good Morning";
public string Name {get;set;}

## Summary

There's a brief introduction into lambda functions, in an upcoming article we'll discuss LINQ, which is where lambda expressions really come into their own, and we see the true power of them.

But as you can see you can convert a multi-line method, into a simple lambda expression to return property values, and is much easier to read.



Enter fullscreen mode Exit fullscreen mode

Top comments (0)