Reputation: 34188
i found a sample code where lambda was used the code as follows
var sumOfgreaterThanSeven = numbers.Sum(n => n > 7 ? n : 0);
but the above code can be written as
var sumOfgreaterThanSeven = numbers.Sum(n > 7 ? n : 0);
so why user write lambda. please help me to understand why user write lambda here. also tell me what is the advantage of lambda. thanks
Upvotes: 2
Views: 379
Reputation: 796
When you write a lambda you are calling a method or evaluating an expression. The left side of the => is a set of parameters passed into the method/expression on the right side.
IEnumerableThing.Where(a => DoSomeStuff(a))
It's like writing this:
foreach (var a in IEnumerableThing)
{
DoSomeStuff(a);
}
In the case of the Sum()
method you are really doing something like this:
int mysum = 0;
foreach (var n in whatever)
{
if (n > 7) { mysum += n; }
}
Upvotes: 2
Reputation: 1062780
The lambda is because you want to evaluate the conditional expression per item n
. The version you added (Sum(n > 7 ? n : 0)
) can't work - n
isn't defined anywhere (the compiler message should be "The name 'n' does not exist in the current context").
The lambda can be read as:
given a term
n
, ifn
is greater than7
returnn
, else return0
and then sum over that logic.
Re the advantage - firstly, convenience - but also composition. For example, with LINQ-to-SQL I would absolutely expect that to issue something like:
select sum(case when row.col > 7 then row.col else 0 end)
from sometable row
of course, it might be better to use:
var sumOfgreaterThanSeven = numbers.Where(n => n > 7).Sum();
which would map to
select sum(row.col)
from sometable row
where row.col > 7
which might hit an index more accurately
Upvotes: 12
Reputation: 81660
You need to think of Lambda Expressions as methods.
n => n > 7 ? n : 0
Can in fact be written as
(n) => {
if(n > 7)
return n;
else
return 0;
}
Lambda expression will be converted to an anonymous method and an instance of Func<>
will be created from it.
As Marc pointed out, this conversion to anonymous method and instance of Func<>
or Action
does not always happen -as rightly pointed out in Linq-to-sql. ... - but here it does, hence I pointed out the underlying.
Upvotes: 2