General Lambda syntax question
So I seem to be confident that the following 2 statements are the same
List<object> values = new List<object>();
values.ForEach(value => System.Diagnostics.Debug.WriteLine(value.ToString()));
AND
List<object> values = new List<object>();
values.ForEach((object value) => {
System.Diagnostics.Debug.WriteLine(value.ToString());
});
AND I know I can insert multiple lines of code in the second example like
List<object> values = new List<object>();
values.ForEach((object value) => {
System.Diagnostics.Debug.WriteLine(value.ToString());
System.Diagnostics.Debug.WriteLine("Some other action");
});
BUT can you do the same thing in the first example? I can't seem to work out开发者_运维问答 a way.
Yes you can :)
List<object> values = new List<object>();
values.ForEach(value =>
{
System.Diagnostics.Debug.WriteLine(value.ToString());
System.Diagnostics.Debug.WriteLine("Some other action");
}
);
This works fine:
values.ForEach(value =>
{ System.Diagnostics.Debug.WriteLine(value.ToString()); }
);
Maybe you forgot the ;
The only real difference between the first and the second is the { }. Add that to the first one and you can then add as many lines as you want. It isn't the (object value) that is allowing you to add multiple lines.
As others have shown, you can use a statement lambda (with braces) to do this:
parameter-list => { statements; }
However, it's worth noting that this has a restriction: you can't convert a statement lambda into an expression tree, only a delegate. So for example, this works:
Func<int> x = () => { return 5; };
But this doesn't:
Expression<Func<int>> y = () => { return 5; };
精彩评论