In previous article, I mentioned Foreach() vs Parallel.Foreach() in C# but now in this article, I have mentioned what are lambda expression in C# and how to use them with various examples using Console Application.
C# Lambda
A lambda expression is an anonymous (unnamed) function not bound to an identifier. Lambda expressions are anonymous functions that contain expressions or sequence of operators.
All Lambda expiression usese lambda operator => which can be called as "goes to" or "become".
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.
Let's take a simple lambda expression example
Func<int, int> multiplyByTen = num => num * 10;
int result = multiplyByTen(5);// Returns 50
The expression num => num * 10
is a lambda expression. The => operator is called the "lambda operator".
In the above example, num
is an input parameter to the anonymous function, and the return value of this function is num * 10
.
A lambda expression has two forms:
Expression lambdas
A lambda expression with an expression on the right side of the => operator is called an expression lambda. An expression lambda returns the result of the expression and takes the following basic form
(input-parameters) => expression
The body of an expression lambda can consist of a method call.
Statement lambdas
A statement lambda resembles an expression lambda except that its statements are enclosed in braces, This form has an expression as its body.
(input-parameters) => { <sequence-of-statements> }
Example:
Action<string> greet = name =>
{
string greeting = $"My Name is {name}!";
Console.WriteLine(greeting);
};
greet("John");
// Output:
// My Name is John
C# Lambda Expression Examples
Let's take a look at few .NET Core Console app lambda expression examples, to understand it better.
Example 1
Suppose, we need to find even numbers from list of numbers, then we can simply use lambda expression (x => x% 2 ) with FindAll Method to get the list of even numbers as shown below:
using System;
using System.Collections.Generic;
namespace LambdaExpressions
{
internal class Program
{
static void Main(string[] args)
{
List<int> listOfNumbers = new List<int>() { 1, 4, 3, 2, 8, 6, 7, 12, 9 , 10 };
//find all event numbers using lambda expression x => x% 2
List<int> evenNumbers = listOfNumbers.FindAll(x => (x % 2) == 0);
//loop through all evenUmbers
foreach (var num in evenNumbers)
{
Console.Write("{0} ", num);
}
Console.ReadKey();
}
}
}
Output:
Example 2
In the above integer list let's try to find square of each number and find numbers less than 6 using Lambda expression.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LambdaExpressions
{
internal class Program
{
static void Main(string[] args)
{
List<int> listOfNumbers = new List<int>() { 1, 4, 3, 2, 8, 6, 7, 12, 9 , 10 };
//using expressions x=> x*x to get sqaure of each number in list
List<int> sqaure = listOfNumbers.Select(x => x * x).ToList();
//print all number squares
foreach (var num in sqaure)
{
Console.Write("{0} ", num);
}
Console.WriteLine();
// use lambda expressions x=> x < 6 with TakeWhile to get numbers less than 6
List<int> numberLessThanSix = listOfNumbers.TakeWhile(x => x < 6).ToList();
//print all number less than six
Console.Write("Numbers less than six are:");
foreach (var num in numberLessThanSix)
{
Console.Write("{0} ", num);
}
Console.ReadKey();
}
}
}
Output:
1 16 9 4 64 36 49 144 81 100
Numbers less than six are:1 4 3 2
Example 3
We can also use Lambda expression with User-defined classes.
using System;
using System.Collections.Generic;
using System.Linq;
namespace LambdaExpressions
{
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
internal class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>() {
new Student { Name = "John", Age = 10 },
new Student { Name = "Miguel", Age = 11 },
new Student { Name = "Brian", Age = 15 }
};
//get names of all students using x => x.Name
var names = students.Select(x => x.Name);
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}
}
Output:
John
Miguel
Brian
That's it, hope it helps.
You may also like to read:
Convert string to char or char array in C#