What is C# Lambdas?
Lambda expressions are how anonymous functions are created. In this article and code examples, we will see how to implement lambdas in C#.
Lambda expressions are anonymous functions that contain expressions or sequences of operators. All lambda expressions use the lambda operator =>, which can be read as “goes to” or “becomes”. The left side of the lambda operator specifies the input parameters, and the right side holds an expression or a code block that works with the entry parameters. Usually, lambda expressions are used as predicates or instead of delegates (a type that references a method).
Expression Lambdas
- Parameter => expression
- Parameter-list => expression
- Count => count + 2;
- Sum => sum + 2;
- n => n % 2 == 0
The lambda operator => divides a lambda expression into two parts. The left side is the input parameter and the right side is the lambda body.
Lambda Expression
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
public static class demo
{
public static void Main()
{
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };
List<int> evenNumbers = list.FindAll(x => (x % 2) == 0);
foreach (var num in evenNumbers)
{
Console.Write("{0} ", num);
}
Console.WriteLine();
Console.Read();
}
}
Output
The preceding example loops through the entire collection of numbers and each element (named x) is checked to determine if the number is a multiple of 2 (using the Boolean expression (x % 2) == 0).
Lambda Example 2
using System;
using System.Collections.Generic;
using System.Linq;
class Dog
{
public string Name { get; set; }
public int Age { get; set; }
}
class demo{
static void Main()
{
List<Dog> dogs = new List<Dog>() {
new Dog { Name = "Rex", Age = 4 },
new Dog { Name = "Sean", Age = 0 },
new Dog { Name = "Stacy", Age = 3 }
};
var names = dogs.Select(x => x.Name);
foreach (var name in names)
{
Console.WriteLine(name);
}
Console.Read();
}
}
Output
We create a collection, containing data from a certain class. In the example, from the class Dog (with properties Name and Age), we want to get a list that contains all the dog's names. With the keyword var, we tell the compiler to define the type of the variable depending on the result that we assigned on the right side of the equals sign.
Using Lambda Expressions with Anonymous Types
using System;
using System.Collections.Generic;
using System.Linq;
class Dog
{
public string Name { get; set; }
public int Age { get; set; }
}
class demo{
static void Main()
{
List<Dog> dogs = new List<Dog>() {
new Dog { Name = "Rex", Age = 4 },
new Dog { Name = "Sean", Age = 0 },
new Dog { Name = "Stacy", Age = 3 }
};
var newDogsList = dogs.Select(x => new { Age = x.Age, FirstLetter = x.Name[0] });
foreach (var item in newDogsList)
{
Console.WriteLine(item);
}
Console.Read();
}
}
Output
The newly created collection newDogsList has elements of an anonymous type taking the properties Age and FirstLetter as parameters.
Sorting using a lambda expression
The following is an examle of sorting with a lambda expression:
var sortedDogs = dogs.OrderByDescending(x => x.Age);
foreach (var dog in sortedDogs)
{
Console.WriteLine(string.Format("Dog {0} is {1} years old.", dog.Name, dog.Age));
}
Output
Thank you.
Here are more articles on Lambda Expressions:
- Beginners Guide to Lambda Expressions
- Lambda Expressions in C# 3.0
- Learn Lambda Expression in 15 Minutes