A lambda expression is an anonymous function that can contain expressions and statements and can be used to create delegates or expression tree type. All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of lambda operator specifies the input parameter if any and right side holds the expression or statement block.
The lambda expression has the same precedence as assignments (=) and is right associative. We can use lambdas in method based LINQ query as argument to slandered query. We cannot use lambda operators on the left side of is or as operator.
We can use following basic form of expression using lambda expression
1) (input parameters) => expression: Here parenthesis are optional if there is only one parameter otherwise it is required.
2) (x, y)=>x==y: We can use this type of lambda expressions when we want to specify input types to the compiler.
3) ()=>SomeMethod(): When we want to create expression trees such as with sql server function then we use these type of lambda expression.
Example which represents lambda expression with collection
/// <summary>
/// In this method we will see use of two method one is use of
/// annoymouse method to search value in collection and other one
/// is by using lambda expression to search. We see that using lambda
/// expression line of code is saved.
/// </summary>
public void lambdaExpression()
{
//Create a collection objects.
List<string> nameCollection = new List<string>();
//Add some values in collection object.
nameCollection.Add("James");
nameCollection.Add("Chow");
nameCollection.Add("John");
nameCollection.Add("Haider");
nameCollection.Add("Amit");
//Using annoymouse expression for checking name
string result = nameCollection.Find(delegate(string name)
{
return name.Equals("John");
});
if (!string.IsNullOrEmpty(result))
Console.WriteLine(result);
else
Console.WriteLine("Specified record is not found.");
//Using lambda expression for checking name
string lambdaResult = nameCollection.Find(sname => sname.Equals("James1")); //Here we directly write name of variable like sname.
if (!string.IsNullOrEmpty(lambdaResult))
Console.WriteLine(lambdaResult);
else
Console.WriteLine("Specified record is not found.");
}
Anonymous User
06-May-2019Thanks for the post.
Ashish srivastava
15-Sep-2015Ashish srivastava
15-Sep-2015Anonymous User
27-Mar-2012http://www.mindstick.com/Blog/289/Introduction%20of%20lambda%20expression
Thanks,
Somesh
27-Jul-2011Usefull blog on Lambda expressions
Other link
http://www.mindstick.com/Blog/84/Lambda%20Expression%20in%20C