Friday, September 11, 2020

Lambda Expression

  • It is an anonymous method which has no access modifier, no name and  no return statement. 
(input-parameters) => expression
  • We can write lambda expression to achieve something with less code. Below example shows how we can write a code to get multiplication of two numbers with lambda expression and without lambda expression. 
  •     class Program
        {
            static void Main(string[] args)
            {
                //args => expression
    
                //Without Lambda Expression
                Console.WriteLine(Square(5));
    
                //With Lambda Expression and Func
                Func<int, int> multiplication = number => number * number;
                Console.WriteLine(multiplication(5));
    
                Console.Read();
            }
    		
    	private static int Square(int x)
            {
                return x * x;
            }
        }
    	
    
  • We can also use lambda expressions when we write LINQ in C#.
  • int[] numbers = { 2, 3, 4, 5 };
    var squaredNumbers = numbers.Select(x => x * x);
    Console.WriteLine(string.Join(" ", squaredNumbers));
    // Output:
    // 4 9 16 25
    
    //Consider new BookRepository().GetBooks() returns list of books
    var listofBooks = new BookRepository().GetBooks();
    List<Books> cheapBooks = listofBooks.FindAll(b => b.price < 20).ToList();
    	
    

No comments:

Post a Comment