Lambda Expression in C#

I think most of .Net coder is familiar with Lambda expression. So it is basically a way to write anonymous function. According to the syntax Lambda expression can take Input and based on the Input and expression it will produce the output. The syntax of the Lambda expression is

(input parameters) => expression or statements.

For example if I have a method with the following body

int Add( int a, int b ){
      return a+b;
}
to
(a,b)=>{ return a+b; } with the contract Func<int, int>. So it will be like below,
Func<int, int> add = (a,b)=>{return a+b;}


There are lots of interesting thing about Lambda expression and Extension methods. In this article I discuss about few stuffs about Lambda and Func then do something with the Extension methods Select and Where of IEnumerable class.

The example of I am to use in this article will have basic lambda and Func along with these there will be IEnumerable class with Select and Where extension methods. In the example Program class will have few basic things about Lambda and Calculator class has few other stuff. I include the code in one chunk.

namespace TestHarness
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Collections;
    class Program
    {
        static void Main(string[] args)
        {
            Action<int> printer = (x) => Console.Write("{0}\t", x);
 
            Func<intintint> funcAdd = (x1, x2) => { return (x1 + x2); };
            Func<intintint> funcAddExtraLogic =
                (x1, x2) =>
                {
                    if (x1 > x2)
                        x1 = x1 * 2;
                    else
                        x2 = x2 * 2;
                    return (x1 + x2);
                };
 
            Console.WriteLine("Lamda expression test: \t{0}", funcAdd(4, 4));
            Console.WriteLine("Lambda expression test:\t{0}", funcAddExtraLogic(4, 4));
 
            Calculator calculator = new Calculator();
            Console.WriteLine("{0}", calculator.Add(4, 4));
            Console.WriteLine("{0}", calculator.Add(calculator.AddImplementator(), 4, 4));
            Console.WriteLine("{0}", calculator.AddImplementator()(4, 4));
 
            Console.WriteLine("Get the list:");
            Console.WriteLine("Using Lambda exrepession.");
            calculator.GetResultUsingExpression().ToList<int>().ForEach(printer);
            Console.WriteLine("Using Lambda exrepession with Func method.");
            calculator.GetResult().ToList<int>().ForEach(printer);
            Console.WriteLine("Using Lambda exrepession with inline delegate implementation");
            calculator.GetResult(x => { return x % 2 == 0; }, x => { return x; }).ToList<int>().ForEach(printer);
 
        }
    }
    public class Calculator
    {
        Func<intintint> mFuncAdd = (x1, x2) => { return (x1 + x2); };
 
        public int Add(int a, int b)
        {
            return mFuncAdd(a, b);
        }
        public int Add(Func<intintint> funcAdd, int a, int b)
        {
            return funcAdd(a, b);
        }
 
        public Func<intintint> AddImplementator()
        {
            return (a, b) =>
            {
                return a + b;
            };
        }
 
        public IEnumerable<int> GetResultUsingExpression()
        {
            int u = 40;
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => x % 2 == 0 && x > u)
                .Select((x) => x * 2);
            return result;
        }
 
        public IEnumerable<int> GetResult()
        {
            int u = 40;
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => Check()(x, u))
                .Select((x) => SelectCondition()(x));
            return result;
        }
 
        public IEnumerable<int> GetResult(Func<intbool> checker, Func<intint> selector)
        {
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => checker(x))
                .Select((x) => selector(x));
            return result;
        }
 
        private Func<intintbool> Check()
        {
            return (int a, int u) =>
            {
                return a % 2 == 0 && a > u;
            };
        }
 
        private Func<intint> SelectCondition()
        {
            return (a) =>
            {
                return a * 2;
            };
        }
    }
}



In the above code I create a delegate Func<int, int,int> funcAdd and  this (x1,x2)=>{return (x1+x2);} anonymous method using Lambda expression. and there is also another delegate named funcAddExtraLogic. I created this one to show how can I use multiple statements.


In the Calculator class I implement few methods to manipulate a list to show the usage of Where and Select extension methods. Where and Select methods have the following signature,

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source,Func<TSource, bool> predicate)

public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source,Func<TSource, TResult> selector)


Following methods manipulate the list using Where and Select. As the signature shows it is extension methods of the IEnumerable and as well it accept a Func with TSource as input parameter and bool as output parameter. From the beginning of this article I showed Func is a  anonymous function, so it uses x=>x%2==0 &&x>u.
public IEnumerable<int> GetResultUsingExpression()
        {
            int u = 40;
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => x % 2 == 0 && x > u)
                .Select((x) => x * 2);
            return result;
        }



on the other hand as Where accept a Func<int, bool> delegate so I implement a method with return type Func<int, bool> and then use that for Where. So the code is as below,

public IEnumerable<int> GetResult()
        {
            int u = 40;
            IEnumerable<int> result = Enumerable
                .Range(0, 100)
                .Where(x => Check()(x, u))
                .Select((x) => SelectCondition()(x));
            return result;
        }


private Func<intintbool> Check()
        {
            return (int a, int u) =>
            {
                return a % 2 == 0 && a > u;
            };
        }




The output of the example is as below,

Lamda expression test:  8
Lambda expression test: 12
8
8
8
Get the list:
Using Lambda exrepession.
84      88      92      96      100     104     108     112     116     120
124     128     132     136     140     144     148     152     156     160
164     168     172     176     180     184     188     192     196     Using La
mbda exrepession with Func method.
84      88      92      96      100     104     108     112     116     120
124     128     132     136     140     144     148     152     156     160
164     168     172     176     180     184     188     192     196     Using La
mbda exrepession with inline delegate implementation
0       2       4       6       8       10      12      14      16      18
20      22      24      26      28      30      32      34      36      38
40      42      44      46      48      50      52      54      56      58
60      62      64      66      68      70      72      74      76      78
80      82      84      86      88      90      92      94      96      98
Press any key to continue . . .


happy to learn from others.

Thanks
mohammad

2 comments:

  1. Really this is a good article, which helps a lot for beginners as me as well as developer. This link...
    http://www.mindstick.com/Blog/181/Lambda%20Expression%20in%20c

    I have found over internet which also explain nicely.

    Thanks!!!

    ReplyDelete