Hello Friends, In this tutorial we are going to learn Lambda Expression. We have already familiar with Delegates and Anonymous Function.

After completing this tutorial you will be able to understand:

  • What is Lambda Expression?
  • How to use Lambda Expression in C#?

Introduction:

The term lambda is not new It has derived from the mathematical term lambda calculus. Lambda expression is a simpler way to define Anonymous method. Lambda operator (=>) is used to define Lambda expression. The => operator can be read as “goes to” or “becomes”. The left side of => operator specifies the lambda expression and right side of => operator specifies the expression or code block.

The expression for defining Lambda Expression:

(input parameters) => Statement or Code Block

Example for defining Lambda Expression:

x => x * 2

Examples for Lambda Expression:

How to find Even Number from a list of Integer:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LambdaExpressionExample
{
 public class Program
 {
 public static void Main(string[] args)
 {
 List<int> lstIntegers = new List<int>() { 1, 2, 3, 4, 5, 6 };
 List<int> lstEvenNumbers = lstIntegers.FindAll(iNumber => (iNumber % 2) == 0);

 foreach (var vNum in lstEvenNumbers)
 {
 Console.Write("{0} ", vNum);
 }
 Console.WriteLine();
 Console.ReadLine(); 
 }
 }
}

Output:

Lambda

Edit Online

Example 2:

Order a list of the string:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LambdaExpressionExample2
{
 public class Technology
 {
 public string LanguageName { get; set; }
 }
 public class Program
 {
 public string LanguageName { get; set; }
 public static void Main(string[] args)
 {
 List<Technology> lstTechnology = new List<Technology>() { 
 new Technology { LanguageName = "C#"}, 
 new Technology { LanguageName = "PHP"}, 
 new Technology { LanguageName = "ASP.NET" },
 new Technology { LanguageName = "SQL Server" },
 new Technology { LanguageName = "Java" },
 new Technology { LanguageName = "MY SQL" },
 }; 
 var sortedTechnologies = lstTechnology.OrderByDescending(x => x.LanguageName);
 foreach (var item in sortedTechnologies)
 {
 Console.WriteLine(string.Format("{0}", item.LanguageName));
 }
 Console.ReadLine();
 }
 }
}

Output:

Lambda

Conclusion:

Hope you are now clear about my this tutorial. I would like to have your Comments, Feedback and Suggestions.

View More:

Thank You.

Leave a Comment