General Lambda syntax question

So, I am sure 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 that I can insert several lines of code in the second example, for example

 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 in the first example? I can't seem to find a way.

+4
source share
4 answers

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"); } ); 
+8
source

This works great:

 values.ForEach(value => { System.Diagnostics.Debug.WriteLine(value.ToString()); } ); 

You may have forgotten ;

+2
source

The only real difference between the first and second is {}. Add this to the first and you can add as many lines as you want. It is not (object value) allowing you to add multiple lines.

+2
source

As others have shown, you can use the lambda statement (with curly braces) to do this:

 parameter-list => { statements; } 

However, it is worth noting that this has a limitation: you cannot convert the lambda operator to an expression tree, but only a delegate. So, for example, this works:

 Func<int> x = () => { return 5; }; 

But this is not so:

 Expression<Func<int>> y = () => { return 5; }; 
+1
source

All Articles