VB.NET Linq Expression with function (x) not running?

Why does this work as expected:

list.ForEach(sub(x) x.Name = "New Name") 

But this is not so:

 list.ForEach(function(x) x.Name = "New Name") 

Anyone else embarrassed?

+4
source share
2 answers

List (Of T) .ForEach takes as an argument Action (Sub), which does not return a value, not Func (Function), which returns a value.

In VB, the = sign is ambiguous. It can be used for comparison or assignment. As a result, in order to find out the statement, x.Name = "New Name" , the team used the Sub or Function indicator to determine if this is a mapping or assignment. In the case of Sub(x) x.Name = "New Name" you assign or set the value of the x Name parameter to "New Name". In the case of Function(x) x.Name = New "Name" you perform a comparison and return if the Name parameter for x is the same as "New Name". As a result, you should be careful when using Sub and Function.

+2
source

If you use the Function keyword

 list.ForEach(Function(x) x.Name = "New Name") 

you create a function that takes an argument named x and returns bool (in this case).

So, in this case, = not an assignment operator, but the comparison operator, therefore, the Name property does not change. (The compiler reports that the function returns bool due to the comparison operator)

It is equivalent

 list.ForEach(sub(x) Foobar(x)) ... Function Foobar(x as Foo) As Boolean Return x.Name = "New Name" 'returns a boolean' End Function 
+5
source

Source: https://habr.com/ru/post/1432286/


All Articles