Whenever we talk about LINQ then everything related to LINQ comes as a part of discussion and so the Lambda Expressions are. Sometimes people ask the question about the Lambda Expression; It look so weird why should I use it in my code and what exactly it stands for? Developers who either from C++ or working on C# 2.0 are still not have clear vision of Lambda Expression. What are Lambda Expressions?, When & Where to use them? These are the basic question that can comes in mind when anybody heard of new programming things.
Through this post I'll try to answer these question. There are new terms are being introduced with every release of .Net framework so lets get started with Lambda Expression for now:
What is Lambda Expression?
Lambda expressions are similar to anonymous methods introduced in C# 2.0, except that lambda expressions are more concise and more flexible. All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.
Lets take an example:
The segment inside the braces of anonymousDel is the also called as Anonymous Function.
Now lets convert it to Lambda Expression:
x => x * 2 is the Expression that is known as Lambda Expression. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * 2 is read "x goes to 2 times x." This reduced the no. of line as you can see and the output is still the same.
The above expression can be generalize for clear understanding.
(input parameters) => Expression;
and can be termed as "Expression Lambdas" since single Expression is involved here.
A Lambda Expression can contain multiple statements and can be surrounded by { } just like anonymous functions.
(input param1, input param2) => { statement1, Statement 2};
For e.g.
You can raise a question here how x & y are being treated as integer while you didn't declared them as integer?
Here is the answer, When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type based on the lambda body, the underlying delegate type, and other factors as described in the C# Language Specification.
Anonymous function that take no parameter and return nothing can be written in form of Lambda Expression like below:
When & Where to use Lambda Expression?
Whenever you came to know about new term and you already know what it is then directly ask yourself when & where it would be used. The Lambda Expressions can be used to simply replacing the Anonymous functions, In the LINQ query methods, or any where you need to intialize Generic delegates.
LINQ Query example:
LINQ to Objects
LINQ to SQL
LINQ To XML
OTHER
Func<>, Action<> and Expression<> are the new generic delgates where you can use Lambda Expressions. Don't panic with these new terms Lets take example where are these new generic delegates can be used.
Look at the below code snippet:
Lets modify the above code snippet using generic delegates and Lambda Expressions
Explanation of Func<int, int, int> would be Func<parameter1, parameter2, returntype>
you can pass any number of argument but last mentioned type would be the type of returned value. Similary we use Action<param1, param2> in this we don't need to return any value. It denotes the Generic delegate here that have return type void. These delegates are introduced to provide the taste of Functional Progamming in the C# itself. if you are still interested in further reading then its worth for me writing this post.
When to use Lambda Expression?
Use whenever you feel reducing your line of code. Keep in mind the code maintainability while reducing the number of code lines. People think Lambda Expression as awkward looking code, But I'm telling you its worth using them in code wisely and once you understood the concept you'll fall in love using them. If you are going to use Excess of LINQ in your code then Lambda Expression will be your favorite buddy helping you wrap your code logic in few lines or may be Inline.
Hope you enjoyed reading this. Thanks for you time please leave comment for any question/suggestion.
Through this post I'll try to answer these question. There are new terms are being introduced with every release of .Net framework so lets get started with Lambda Expression for now:
What is Lambda Expression?
Lambda expressions are similar to anonymous methods introduced in C# 2.0, except that lambda expressions are more concise and more flexible. All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.
Lets take an example:
delegate int anonymousDel(int i);
anonymousDel myDelegate = new anonymousDel(
delegate(int x)
{
return x * 2;
});
Console.WriteLine("{0}", myDelegate(5));
anonymousDel myDelegate = new anonymousDel(
delegate(int x)
{
return x * 2;
});
Console.WriteLine("{0}", myDelegate(5));
The segment inside the braces of anonymousDel is the also called as Anonymous Function.
Now lets convert it to Lambda Expression:
anonymousDel myDelegate = x => x * 2;
x => x * 2 is the Expression that is known as Lambda Expression. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * 2 is read "x goes to 2 times x." This reduced the no. of line as you can see and the output is still the same.
The above expression can be generalize for clear understanding.
(input parameters) => Expression;
and can be termed as "Expression Lambdas" since single Expression is involved here.
A Lambda Expression can contain multiple statements and can be surrounded by { } just like anonymous functions.
(input param1, input param2) => { statement1, Statement 2};
For e.g.
anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };
Console.WriteLine(getBigInteger(10,15));
Console.WriteLine(getBigInteger(10,15));
You can raise a question here how x & y are being treated as integer while you didn't declared them as integer?
Here is the answer, When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type based on the lambda body, the underlying delegate type, and other factors as described in the C# Language Specification.
Anonymous function that take no parameter and return nothing can be written in form of Lambda Expression like below:
delegate void doSomething();
doSomething IamVoid = () => { Console.WriteLine("Hello there! I take nothing and return nothing"); };
//call the Anonymous function
IamVoid();
doSomething IamVoid = () => { Console.WriteLine("Hello there! I take nothing and return nothing"); };
//call the Anonymous function
IamVoid();
When & Where to use Lambda Expression?
Whenever you came to know about new term and you already know what it is then directly ask yourself when & where it would be used. The Lambda Expressions can be used to simply replacing the Anonymous functions, In the LINQ query methods, or any where you need to intialize Generic delegates.
LINQ Query example:
LINQ to Objects
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
int oddNumbers = numbers.Count(n => n % 2 == 1);
LINQ to SQL
Customers.Where(c => c.City == "London");
LINQ To XML
var xml1 = element.Descendants("customer").Where(cust => cust.Attribute("id").Value == CustomerId).SingleOrDefault();
OTHER
Func<>, Action<> and Expression<> are the new generic delgates where you can use Lambda Expressions. Don't panic with these new terms Lets take example where are these new generic delegates can be used.
Look at the below code snippet:
delegate int anonymousDel2(int a, int b);
anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };
Console.WriteLine(getBigInteger(10,15));
anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else return y; };
Console.WriteLine(getBigInteger(10,15));
Lets modify the above code snippet using generic delegates and Lambda Expressions
Func<int, int, int> getBigInteger = (x, y) => { if (x > y) return x; else return y; };
Console.WriteLine(getBigInteger(10,15));
Console.WriteLine(getBigInteger(10,15));
Explanation of Func<int, int, int> would be Func<parameter1, parameter2, returntype>
you can pass any number of argument but last mentioned type would be the type of returned value. Similary we use Action<param1, param2> in this we don't need to return any value. It denotes the Generic delegate here that have return type void. These delegates are introduced to provide the taste of Functional Progamming in the C# itself. if you are still interested in further reading then its worth for me writing this post.
When to use Lambda Expression?
Use whenever you feel reducing your line of code. Keep in mind the code maintainability while reducing the number of code lines. People think Lambda Expression as awkward looking code, But I'm telling you its worth using them in code wisely and once you understood the concept you'll fall in love using them. If you are going to use Excess of LINQ in your code then Lambda Expression will be your favorite buddy helping you wrap your code logic in few lines or may be Inline.
Hope you enjoyed reading this. Thanks for you time please leave comment for any question/suggestion.
Like it... its very good for Linq beginners....
ReplyDeleteWell explained...
ReplyDeleteThanks Kunal. It means a lot to me.. :)
ReplyDeleteVery good post, clarified some doubts I had. Thanks a lot.
ReplyDeletevery good introduction to lambda expressions.each step is well broken down with explanation.Thank you Michael G.
ReplyDeleteVery good...I was looking for this kind of easy intro.. Thanks a lot!.. Keep going...
ReplyDeleteReally good explanation thanks.
ReplyDeletenice one
ReplyDeleteSimple explanation but covered lot of things...thanks,
ReplyDeletevery much usefull
ReplyDeleteVery useful.
ReplyDeleteReally Awesome
ReplyDeleteIt is really helping code
ReplyDeleteReally very helpful lines. Amit Please give a print option in your website like www.codeproject.com and MSDN
ReplyDeleteThanks
It's good for beginers, nice post
ReplyDeleteWell explained...
ReplyDeleteGood and wisely written article. Now i will use them in my code.
ReplyDeleteThanks, it really helpful
ReplyDeleteVery goog for beginers.
ReplyDeleteSuperb article.....
ReplyDeleteWonderful man...Covered almost everything in an easy to understand way. Thank you.
ReplyDeleteit is nice description about lambda
ReplyDeleteTHanks for this
That was a great explanation. However, if I could make a somewhat related suggestion for your code I would say that you should replace your if-else statements with the conditional ?: operator where you start with a boolean expression, and if it evaluates to true the first expression is evaluated, and if false the second expression is evaluated. It takes the form of
ReplyDelete(boolean statement) ? (Do this if true) : (do this if false);
Very good
ReplyDeleteThis comment has been removed by the author.
DeleteIt is very hekpful to me to know about Lambda Expression.Thanks alot for ur post
DeleteReally helpful
ReplyDeleteExcellent article on Lamda Experssion..
ReplyDeleteThanks alot it very helpful.
ReplyDeletegreat explanations...
ReplyDeleteNice article..
ReplyDeleteLamba Expression using Anonymous type:
ReplyDeleteusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linq_Basics
{
class Program
{
static void Main(string[] args)
{
string[] names = {"Amar","vicky","Bala","sankar","vimal" };
var lambfilter = names.Select(c => new { Namelength = c.Length, Name = c });
foreach (var v in lambfilter)
{
Console.WriteLine("The {0} name of length {1}",v.Name,v.Namelength);
}
Console.ReadKey();
}
}
}
its very useful to all.thank u ........... then please provide the explanation about FirstOrdefault()
ReplyDeleteNice explanation, I like it than you!!
ReplyDeleteAnil SIngh
http://www.code-sample.com/