i found a sample code where lambda was used the code as follows
var sumOfgreaterThanSev开发者_StackOverflowen = 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
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
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.
UPDATE
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.
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; }
}
精彩评论