This is a small article which talks about lambda expression which we use it in our daily coding. We usually use lambda expression for querying through the collection or for calculating the formulas. But have you ever thought of why we use that weird syntax and how it helps us.
Talking about Lambda expression I can say, it is an anonymous function used to create delegates in LINQ. It can also be said like- it is a method without name, access modifier and return value. It allows you to write a method in the same place you are going to use it.
We should keep in mind that Lambda expression should be short enough in functionality. A complex definition makes the calling code difficult to read.
Syntax:
Parameters => Executed code
To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side.
Example:
Where a is an input parameter and a*2 ==10 is the expression which is executed.
- List<string> names = new List<string> { "pradeep", "rock", "frank", "robben" };
- var myname = names.Where(n => n == "pradeep")
- .Select(d => d);
In above example, iterate through the collection to find my name.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.
Similarly we will take one more example where I want to calculate cube of a number:
- delegate int Cube(int number);
- static void Main(string[] args)
- {
- Cube delegtateCall = x => x * x * x;
- int result = delegtateCall(10);
- }
Conclusion:
A lambda expression is an anonymous function which can be used once when created. It really makes our work faster and easy. Hope you like this small article. Share your comments whether it’s good or bad. Sharing is valuable no matter what :).