Tags

, ,


Lambda Expressions

Business an people ask for and need evermore powerful software applications. For programmers, this means code has to do more. Creating  code is a function of time and money. Programmers need to be able to use higher and higher levels of abstraction to write code that does more with less and that consume s less time and money. All of this implies code compression-fewer bits of code to do substantially more, hence Lambda Expressions.
Thinks of Lambda Expression as brief inline functions whose concise nature is an ideal fit for LINQ. Brian Kernighan and Dennis Ritchie brought us function pointers in C. A function is referenced by an address, which is just a number, after all. Function pointers led to the notion of events- really just function pointers-and event handlers evolved into delegates and multicast delegates in .net. Delegate compress into anonymous delegate in .net 2.0. Anonymous delegate lost some weight by eliminating the function name, return type and parameters type, and anonymous expression have evolved into lambda Expression.

Following examples will take you for Delegates to Generic Delegate (Lambda Expression)

1.  Simple Delegate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MyLinq.Lambda
{
    public class Lambda
    {
        private delegate void FunctionPointer(string s);
        public static void Main(string[] args)
        {
            FunctionPointer fp=new FunctionPointer(Word);
            fp(“\n”);
            fp(“Delegate”);
            fp(“C# and Delegate is the gr8 Combination”);
            fp(“Currentrly i am using the simple example of delegate”);
            Console.Read();
        }
       
        private static void Word(string s)
        {
            Console.WriteLine(s);
        }

}

2.  Anonymous Delegate

Anonymous delegate lost some weight by eliminating the function name, return type and parameters type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MyLinq.Lambda
{
    public class Lambda
    {
        private delegate void AnonymousFunctionPointer(string s);
        public static void Main(string[] args)
        {
            AnonymousFunctionPointer afp=delegate(string s)
                                                                                  {
                                                                                      Console.WriteLine(s);
                                                                                  };
            afp(“\n”);
            afp(“Anonymous Delegate”);
            afp(“Delegate compress into anonymous delegate in .net 2.0.”);
            afp(“Anonymous delegate lost some weight by eliminating the function name, return type and parameters type”);
            Console.Read();
        }

3. Lambda Expression Delegate

Lambda Expression (=>) play the Role of Delegate. Lambda Expression eliminate the delegate keywords, function header, parameter types, brackets, and return keyword.  This very concise grammar for Lambda Expressions is not plain old esoterrorism. Lambda Expression’s concise nature makes it easy for these smallish functions to fit into new constructs that support LINQ.

A Lambda Expression is concise delegate. The left side (of =>) represents the arguments of the function and the right side is the function body. The Lambda Expression is assigned to the delegate function pointer, but in .net 3.5 defines anonymous delegate delegates like Action<t> and Fun<t>, which can be used instead of the more formal, longer delegate statement. This means that you don’t have to define the delegate statement with the generic Action<t> delegate type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MyLinq.Lambda
{
    public class Lambda
    {
        private delegate void LembdaFunctionPointer(string s);
        public static void Main(string[] args)
        {
            LembdaFunctionPointer lfp=s=>Console.WrireLine(s);
            lfp(“\n”);
            lfp(“Lembda Expression Delegate”);
            lfp(“Anonymous expression have evolved into lambda Expression”);
            Console.Read();
        }

4. Generic Delegate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MyLinq.Lambda
{
    public class Lambda
    {
        public static void Main(string[] args)
        {
            System.Action<string> gd=s=>Console.WriteLine(s);
           
gd(“\n”);
            gd(“Generic Delegate”);
            gd(“Simple, Powerfull, easy……….!”);
            Console.Read();
        }

Basic Lambda Expression

System  namespace define generic delegates Action, Func and Predicate. Action performs an operation on the generic arguments.  Func performs an operation on the argument or arguments and returns a value, andPredicates<T> is used to represent a set of criteria and determine if the argument match the criteria. A lambda expression can be used as literal expressions to methods that accept Fun, Action or Predicate arguments.

Reading Lambda Expression

Lambda Expression  are written  with a left side, the => symbol and a right side, as in (x,y)=>x+y; . The left side represents the input arguments and the right side is the expression to be evaluated.
Ex.: (x,y)=>x+y;
or also can rewritten as
(int x, int y)=>x+y;

Use of Func<>

namespace MyLinq.Lambda
{
    public class Lambda
    {
        public static void Main(string[] args)
        {

//Lambda Expression

Func<int,int,int>add = (i,j) => i + j;

Console.WriteLine(add(10,20));
    }
  }
}

Use of Action

namespace MyLinq.Lambda
{
    public class Lambda
    {
        public static void Main(string[] args)
        {

Action<double> print = s => { Console.WriteLine(“Amount {0:c}”, s); };
Action<double>  calc = (amount) => print(amount*.10);
var amounts = new double[] {1000,2000,3000,20,100,2343,09};

Array.ForEach<double>(amounts, calc);
   }
  }
}

 Use of Predicate

namespace MyLinq.Lambda
{
    public class Lambda
    {
        public static void Main(string[] args)
        {
             List<int> nos=new List<int>();
     nos.AddRange(new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18});
     Predicate<int> match = n => n%2 == 1;
     var ods = nos.FindAll(match);
     Array.ForEach<int>(ods.ToArray<int>(),n=>Console.WriteLine(n));
    }
  }
}

 

Lambda Expression captured as Generic Action

namespace MyLinq.Lambda
{
    public class Lambda
    {
        public static void Main(string[] args)
        {     
            Action<string, TextWriter> printText = (s, write) => {write.Write(s);};
     StreamReader sr = new StreamReader(@”C:\Data\InfoCom\program files\Infocom Trade Directories\Info.dat”);
     while (!sr.EndOfStream)
           printText(sr.ReadLine(), System.Console.Out);
  }
 }
}

Searching String

namespace MyLinq.Lambda
{
    public class Lambda
    {
        public static void Main(string[] args)
        {     
              List<string> lstName=new List<string>();
      lstName.AddRange(new String[]{ “Jitendra”, “Ghanshyam”, “Amit”, “Sumit”, “Rohit”, “Manish”, “Ronit”, “Manmohan”, “Soniya”});
      Predicate<string> pList=s=>s.Contains(“m”);
      var lstNm=lstName.FindAll(pList);
      Array.ForEach<string>(lstNm.ToArray<string>(),s=>Console.WriteLine(s));
   }
  }
}

Binding Control Event to Lambda Expression

namespace MyLinq.Lambda
{
    public partial class Lambda:Form
    {
        public Lambda()
        {
             button1.Click +=(s,o)=>MessageBox.Show(“Click”);
        }
    }
}

 

Dynamic Programming with Lambda Expression

Using Select<T>

namespace MyLinq.Lambda
{
    public partial class Lambda:Form
    {
        public static void Main(string[] arg)
        {
            var namesSearch = new string[] { “Jitendra”, “Ghanshyam”, “Amit”, “Sumit”, “Rohit”, “Manish”, “Ronit”, “Manmohan”, “Soniya” };

     foreach (var name in namesSearch.Select(nm=>nm))

     {

        Console.WriteLine(name);

     }

     //Change Expression with Named Type

     namesSearch = new string[] { “Manoj Shri”, “Rohit Sharma”, “Jitendra”, “Ghanshyam”, “Amit”, “Sumit”, “Rohit”, “Manish”, “Ronit”, “Manmohan”, “Soniya” };

     foreach (var name in namesSearch.Select(s=>new{item=s,IsContains=s.Contains(“G”)}))

     {

        Console.WriteLine(name.item);

     }
        }
    }
}
Using Wheere<T>

namespace MyLinq.Lambda
{
    public partial class Lambda:Form
    {
        public static void Main(string[] arg)
        {
     var namesWhere = new string[] { “Manoj Shri”, “Rohit Sharma”, “Jitendra”, “Ghanshyam”, “Amit”, “Sumit”, “Rohit”, “Manish”, “Ronit”, “Manmohan”, “Soniya” };

     IEnumerable<string> nw = namesWhere.Where(nm => nm.Contains(“i”) && nm.Contains(“a”)) ;

     foreach (var name in nw)

     {

       Console.WriteLine(name);

     }
     //Whare
     var Names = new string[] {“Jitendra”,”Ghanshyam”,”Amit”,”Sumit”,”Rohit”,”Manish”,”Ronit”,”Manmohan”,”Soniya”};

     var result = Names.Where(s => s.Contains(“it”));
     Array.ForEach<string>(result.ToArray<string>(),s=>Console.WriteLine(s));
        }
    }
}

 

Using OrderBy<T>

namespace MyLinq.Lambda
{
    public partial class Lambda:Form
    {
        public static void Main(string[] arg)
        {
      var namesOrder = new string[] { “Manoj Shri”, “Rohit Sharma”, “Jitendra”, “Ghanshyam”, “Amit”, “Sumit”, “Rohit”, “Manish”, “Ronit”, “Manmohan”, “Soniya” };

      IEnumerable<string> nwo = namesOrder.OrderBy(nm => nm);

      foreach (var name in nwo)

      {

         Console.WriteLine(name);

      }

        }
    }
}

Using OrderByDessending<T>

namespace MyLinq.Lambda
{
    public partial class Lambda:Form
    {
        public static void Main(string[] arg)
        {
      //Order Desc

      var namesOrderD = new string[] { “Manoj Shri”, “Rohit Sharma”, “Jitendra”, “Ghanshyam”, “Amit”, “Sumit”, “Rohit”, “Manish”, “Ronit”, “Manmohan”, “Soniya” };

      IEnumerable<string> nwoD = namesOrderD.OrderByDescending(nm => nm);

      foreach (var name in nwoD)

      {

        Console.WriteLine(name);

      }
        }
    }
}

Currying

Carrying is a use of Lambda Expression in which a multistep expression is broken into several Lambda Expressions. Each Lambda Expression is a feeder to the next expression until the last expression provides the solution. This is sort of like a Turning macthine.

namespace MyLinq.Lambda
{
    public partial class Lambda:Form
    {
        public static void Main(string[] arg)
        {
      Func<int, int, int> longAdd = (a, b) => a + b;

      Console.WriteLine(longAdd(20,10));

     //Currying
      Func<int, Func<int, int>> Carrying =a=>b=> a + b;
      Console.WriteLine(longAdd(20, 10));
        }
    }
}

Advertisements