4 different uses of lambda expression in C#
4 uses of lambda expression in C#
In this tutorial we will see 4 different
ways to use lambda expression in C#. If you have used Entity framework or LINQ ,
you probably aware of lambda expression. Here, we will see few situations where
we can use lambda expression.
Search from Collection
If we want to search some element from
List (or generic list) we can use lambda expression. Have a look on below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern
{
class Program
{
static void Main(string[] args)
{
List<int> Lst = new List<int>();
Lst.Add(100);
Lst.Add(200);
Lst.Add(300);
int Value = Lst.Find(m => m.Equals(100));
Console.WriteLine(Value);
Console.ReadLine();
}
}
}
Find series of number
Here is another example of lambda expression, In below
example we have used it to find all even number from collection.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern
{
class Program
{
//Find Even Number
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
var evens = numbers.FindAll(n => n % 2 == 0);
foreach (int a in evens)
{
Console.WriteLine(a);
}
Console.ReadLine();
}
}
}
Use in place of function
No need to write function when task is very little. We can
use lambda expression associate with delegate.
In below example we have set one delegate which will perform square
operation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern
{
class Program
{
delegate int del(int Value);
static void Main(string[] args)
{
del MyDelegate = X => X * X;
Console.WriteLine("Result is := " + MyDelegate(5));
Console.ReadLine();
}
}
}
Use with Func keyword
we can use lambda expression with Func keyword. It will behave like anonymous
function. The first parameter is input type and the second one is output type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern
{
class Program
{
//Find Even Number
static void Main(string[] args)
{
int mulitplyby = 2;
Func<int, int> operation = x => x * mulitplyby;
Func<string, string> Concationation = x => x + "Kayal";
Console.WriteLine("Multiple of 2 is= " + operation(2));
Console.WriteLine("FullName is := " + Concationation("Sourav"));
Console.ReadLine();
}
}
}
Conclusion:-
In this article we have seen how to use lambda expression in various ways. Hope you have enjoyed this article.