Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vb.net

linq

Why is this working as expected:

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

But this isn't:

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

Anyone else confused?

like image 879
Baine Wedlock Avatar asked Sep 04 '12 13:09

Baine Wedlock


2 Answers

When you are using the Function keyword

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

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

So, in this case, = is not the assignment operator, but the comparison operator, hence the Name property is not changed. (The compiler infers that the function returns a bool due to the comparison operator)

It's equivalent to

list.ForEach(sub(x) Foobar(x))

...

Function Foobar(x as Foo) As Boolean
    Return x.Name = "New Name" 'returns a boolean'
End Function
like image 179
sloth Avatar answered Oct 24 '22 07:10

sloth


List(Of T).ForEach takes as an argument an Action (Sub) that doesn't return a value not a Func (Function) that does return a value.

In VB the = sign is ambiguous. It can either be used for comparison or assignment. As a result to disambiguate the statement, x.Name = "New Name" the team used the indicator Sub or Function to identify if this is a comparison or assignment. In the case of Sub(x) x.Name = "New Name", you are performing an assignment, or set the value of x's Name parameter to "New Name". In the case of Function(x) x.Name = New "Name" you are doing a comparison and returning if the Name parameter of x is the same as "New Name". As a result, you have to be careful when you use Sub and Function.

like image 21
Jim Wooley Avatar answered Oct 24 '22 08:10

Jim Wooley