Tuesday, April 29, 2008

LAMBDA expression

I was searching for why should we use LAMBDA expression in LINQ and I found following conclusion from my RND.
LAMBDA expression is a little complex extension in C# 3.0 which is somehow related to Anonymous methods which is available in .NET 2.0.
To get friendly with LAMBDA expression you should have knowledge regarding Delegates and Anonymous method in C#.
There are two types of queries in LINQ
1. Using Query Operators (This use LAMBDA expression)
2. Using Query Expression(This are the simple queries)

1. Using Query Operators
Query operators are static methods that allow the expression of queries

var processes =
Process.GetProcesses()
.Where(process => process.WorkingSet64 > 20*1024*1024)
.OrderByDescending(process => process.WorkingSet64)
.Select(process => new { process.Id,Name=process.ProcessName });









2. Using Query Expression
You can use another syntax that makes LINQ queries resemble SQL queries.

var processes =
from process in Process.GetProcesses()
where process.WorkingSet64 > 20*1024*1024
orderby process.WorkingSet64 descending
select new { process.Id, Name=process.ProcessName };

The above both syntaxes would be giving the same result. But when you use a query expression, the compiler automatically translates it into calls to standard query operators (LAMBDA expression).

Because query expressions compile down to method calls, they are not necessary: We could work directly with the query operators. The only advantage of query expressions is that they allow for greater readability and simplicity. While Query Operators(LAMBDA expression) would give you a little better performance as after all Query expression are going to be compiled to Query operators(LAMBDA expression).

For more refer to the book LINQ in ACTION available in Reference at 10.0.0.2.

No comments: