Using lambda expressions. - CSharp Custom Type

CSharp examples for Custom Type:Lambda

Description

Using lambda expressions.

Demo Code

using System;/*www  .ja  va 2 s. co  m*/
using System.Collections.Generic;
class Lambdas
{
   // delegate for a function that receives an int and returns a bool
   public delegate bool NumberPredicate(int number);
   static void Main(string[] args)
   {
      int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
      // create an instance of the NumberPredicate delegate type using an implicit lambda expression
      NumberPredicate evenPredicate = number => number % 2 == 0;
      // call a lambda expression through a variable
      Console.WriteLine($"Use a lambda-expression variable: {evenPredicate(4)}");
      // filter the even numbers using a lambda expression
      List<int> evenNumbers = FilterArray(numbers, evenPredicate);
      DisplayList("\nUse a lambda expression to filter even numbers: ",evenNumbers);
      // filter the odd numbers using an explicitly typed lambda expression
      List<int> oddNumbers = FilterArray(numbers, (int number) => number % 2 == 1);
      // display the result
      DisplayList("\nUse a lambda expression to filter odd numbers: ", oddNumbers);
      // filter numbers greater than 5 using an implicit lambda statement
      List<int> numbersOver5 = FilterArray(numbers, number => {return number > 5;});
      // display the result
      DisplayList("\nUse a lambda expression to filter numbers over 5: ", numbersOver5);
   }
   private static List<int> FilterArray(int[] intArray, NumberPredicate predicate)
   {
      var result = new List<int>();
      foreach (var item in intArray)
      {
         // if the element satisfies the predicate
         if (predicate(item))
         {
            result.Add(item); // add the element to the result
         }
      }
      return result; // return the result
   }
   private static void DisplayList(string description, List<int> list)
   {
      Console.Write(description);
      foreach (int item in list)
      {
         Console.Write($"{item} ");
      }
   }
}

Result


Related Tutorials