Monday, 9 July 2018

012 LINQ Lambda Expression

'lamdba' is mathematical terms , it is a branch of calculus called Lamdba calculus. Lamdba represent a way of express query in a short and meaningful format with a function definition. Lambda expression execute and return data to the output during the run time execution of program. Below the syntax how Lamdba expression.

Input=> expression or statement


The expression can be simple calculation like square ,round,average or a complex calculation like factorial , selection of data causing multiple where conditions or a complex joining. Here is some example how Lambda expression is written


1)Simple calculation (Square)

   
       DelType doSqare = (value1) =>
      {
            return value1 * value1;
       };

2)Average 

  
       int[] marks = { 10, 20, 30, 40, 50, 60 };
      double highmarks = marks.Average(n => n);


3)Select

         
     int[] marks = { 10, 20, 30, 40, 50, 60 };
     int highmarks = marks.Where(n => n > 40).Count();


4)Joining


       var query = students.Join(students2,
            a => a.roll,
            b => b.roll,
            (a, b) => new { a.name, a.roll, b.address });

5)Order by
   var query = from s in students
               order by s.name, s.age
               select s;


In the first example , you have seen that simple number calculation  that  calculate square of a number. '=>' expression state that it is a Lambda expression and after the execution , return the result to the output. However, it is a part of a code, you cannot write code  in this way, below is the example of how the square can be implemented in Lambda expression with full source code. 


------------------------------
 
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.Linq;
using System.Collections;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
               class Program
               {
                       delegate int DelType(int i);

                       static void Main(string[] args)
                       {
                          DelType doSqare = (value1) =>
                          {
                              return value1 * value1;
                          };

                          int i = doSqare(10);

                          Console.WriteLine(i.ToString());

                         Console.ReadKey();
                     }
          }
}

Output :100

-------------------------------
"DelType" is a delegate which one accept one parameter and return the square of the parameters. You can send more than one parameter to the expression through the delegate method, below is the example how you can send more than one parameter to the Lambda expression and how result food can be  return to the output. 

------------------------------

 
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.Linq;
using System.Collections;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
            class Program
           {
                 delegate int DelType(int i,int l);

                static void Main(string[] args)
                {
                     DelType doSqare = (value1, value2) =>
                     {
                            return value1 * value2;
                      };

                       int i = doSqare(10,20);

                       Console.WriteLine(i.ToString());

                         Console.ReadKey();
               }
          }
}


Output :200
---------------------------------


Expression tree


Expression tree is tree like data structure, every node is  expression. Expression trees is in memory representation of expression .You have to include "System.Linq.Expressions" namespace
to implement expression tree.Here is the example of
Expression tree
----------------------------------


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.Linq;
using System.Collections;
using System.Xml;
using System.Xml.Linq;
using System.IO;

using System.Linq.Expressions;

namespace ConsoleApplication1
{
               class Program
               {

                   static void Main(string[] args)
                   {
                              Expression<Func<string, string, string>> StringConcate = (str1, str2) => string.Concat(str1, str2);
                             var result = StringConcate.Compile()("Hellow ", " World");
                             Console.WriteLine(result);
                             Console.ReadKey();
                   }
          }
}

------------------------------------





Standard query operator

Standard query operator to the number expression is available in LINQ. You can put your required condition on the Standard query operator to get the required result. Below the query fetch only  those data whose modulus is 1.

------------------------------------


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.Linq;
using System.Collections;
using System.Xml;
using System.Xml.Linq;
using System.IO;

using System.Linq.Expressions;

namespace ConsoleApplication1
{
         class Program
         {

              static void Main(string[] args)
              {

                       int[] marks = { 10, 21, 35, 40, 50, 61 };
                       double modValue = marks.Where(a =>a % 2 == 1).Average();

                       Console.WriteLine(modValue.ToString());

                       Console.ReadKey();
             }
        }
}


Output :39

------------------------------------

Asynchronous Lamdba


Lamdba expression also work with asynchronous processing , "async" keyword is used for Lambda expression functions .




Type inference

Type inference one of the major drawback of C# , you cannot infer the type. For example



var t = () => 5;

The code will not compile. Lambda expression allow to type infer 
 
Func<int> f = () => 4;

here is the full code
---------------------------


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
using System.Linq;
using System.Collections;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
             class Program
            {
                    static void Main(string[] args)
                    {
                        Func<int> f = () => 4;
                        Console.ReadKey();
                    }

        }
}

--------------------------


No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...