Specializations

Wednesday, November 14, 2012

Lambda expressions in c#.net with Examples

A lambda expression is an anonymous function that you can use to create delegates or expression tree types.
By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls.
 Lambda expressions are particularly helpful for writing LINQ query expressions.
Lambda expression is an inline delegate introduced with C # 3.0 language.
Although Lambda expressions are simpler to use than anonymous methods, they do slightly differ on how they are implemented.
Both anonymous methods and Lambda expressions allow you define the method implementation inline, however, an anonymous method explicitly requires you to define the parameter types and the return type for a method.
Lambda expression uses the type inference feature of C# 3.0 which allows the compiler to infer the type of the variable based on the context.

Parameters => execution codes or expression.
 
The left hand side represents zero or more parameters followed by the lambda symbol => which is used to separate the declaration of a parameter from the implementation of the method. Lambda expression is then followed by the statement body.
Lambda expression allows us to pass functions as arguments to a method call. I will start with a simple example of lambda expression which returns even numbers from a list of integers.


Example 1
    public static void LambdExpressionExample1()
    {
        List<int> numbers = new List<int>{1,2,3,4,5,6,7,8,9};
        var evens = numbers.FindAll(n => n % 2 == 0);
        var evens2 = numbers.FindAll((int n) => { return n % 2 == 0; });
        Response.Write(evens);
        Response.Write(evens2);
    }

 
Looking at the first lambda expression assigned to the evens variable, you will notice few things that are different from anonymous methods. First, we are not using delegate keyword anywhere in our code. Second, we are not defining the parameter and return types because the compiler infers the type based on context. The types in the expression are determined by the delegate definition. So in this case return type specified by the FindAll method takes a delegate which takes an int parameter and returns boolean. Lambda expression without braces and return type, provides the most concise way to represent anonymous methods. If the number of parameters is one then you can omit the parentheses surrounding the parameter as demonstrated in the first lambda expression. Although lambda expression does not require explicit parameters, you have the option to define the parameters, braces and return type as shown in the second lambda expression assigned to the even2 variable. Notice that we are using the explicit parameter of int and also use the return type as we usually specify in a method. The return statement would not work if you do not enclose the execution code with parentheses considering that you are fully qualifying everything that attributes a method.
Another place where parentheses are required in lambda expressions is when you want to use a parameter in multiple blocks of code inside the lambda expression such as follows:

 Example 2:
delegate void WriteMultipleStatements(int i);
    public static void MultipleStatementsInLamdas()
    {
        WriteMultipleStatements write = i =>
            {
                Console.WriteLine("Number " + i.ToString());
                Console.WriteLine("Number " + i.ToString());
            };
            write(1);
    }


Data table with Lambda expression:

Delete a datatable record using lambda expression

  YourDataTable.AsEnumerable().Where(p => p["Your Column Nmae"].ToString().Trim() == Conditionvalue1 && p["Your another Column Nmae"].ToString().Trim() == Conditionvalue2).ToList().FirstOrDefault().Delete();



Delete() is use full to delete the record into data table. based on your expression your get one or more records if your are using "FirstOrDefault()" your get only one record so you can delete one record only.


GRIDVIEW WITH LINQ AND LAMBDA

 Getting Grid view seleted valuesusing link
Step 1: you must stored the uniq value in label hidden field or label fields. your grid datasource must list values. explame: grid.datasource=List<myClass>();
Step 2: checked gridview rows values are stored into one variable datatype is "var"
Step3: Var values converted into array
Step4: array values find in your list values, then your can modified or removed from your list


Example :
Step 1:
List<myClass> MyList=new List<myClass>();
mygrid.DataSource=myList;
mygrid.Databind();
Step 2:
var checkedIDs = from GridViewRow msgRow in YourGirdView.Rows
                        where ((CheckBox)msgRow.FindControl("YourCheckBoxID")).Checked
                          select ((Label)(msgRow.FindControl("YourLableID"))).Text;

Step 3:
//convert  checkedIDs  to list

string[] poids = checkedIDs.ToArray();
 Step 4:
//list view content updation
limyClass.Where(x => x.POID == p).ToList().ForEach(delegate(myClass di)
               {
                 if (di.STATUS == "N")
                  // remove form your list use this line     liEXPSOPO.Remove(di);
                  //if you want to change any colum value use    di.MyClassValue="MyNewValue";
                  else di.STATUS = "R";
              });




No comments:

Post a Comment