Friday 30 August 2013

Lambda Expressions

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

namespace ConsoleLambda
{
    class Program
    {
        public static double WArea(int a)
        {
            return 3.12 * a * a;
        }
        delegate double CalcArea(int r);
        static void Main(string[] args)
        {
            Console.WriteLine("Without Lambda");
            CalcArea Wca = new CalcArea(WArea);
            Console.WriteLine(Wca(10));

            Console.WriteLine("\n\nSimple Lambda");
            // Need to make new delegate. Lambda makes the code short and simple.
            CalcArea ca = r => 3.12 * r * r;
            Console.WriteLine(ca(10));

            Console.WriteLine("\n\nLambda + Func");
            /*No need to make new delegate. Func<> is the predefined generic function in delegate.
            function, takes the value and gives you new value on the based code behind.*/
            Func<double, double> MyFunc = r => 3.12 * r * r;
            Console.WriteLine(MyFunc.Invoke(10));
           
            Console.WriteLine("\n\nLambda + Action");
            /*No need to make new delegate. Action<> is the predefined generic function in delegate.
            Action, takes the value and shows the value on console.*/
            Action<string> MyAction = r => Console.WriteLine(r);
            MyAction.Invoke("Hello World!");
           
            Console.WriteLine("\n\nLambda + Predicate");
            Console.Write("Enter the string: ");
            string name = Console.ReadLine();
            //this line checking the word 'Entered String' is greater then 3 or not. and returs Boolean Value.
            Predicate<string> MyPredicate = z => z.Length > 3;
            Console.WriteLine(MyPredicate.Invoke(name)+"\n\n\n");
        }
    }
}






Lambda Source Code

No comments: