What's the equivalent VB.NET syntax for anonymous types in a LINQ statement?
Solution 1
new { ... }
becomes
New With { ... }
in VB.NET,
or
New With {Key ... }
if you want to use Key properties (which allows you to compare two anonymous type instances but does not allow the values of those properties to be changed).
So I'm guessing your statement would look like:
.Select(Function(ci) New With {Key _
.CartItem = ci, _
.Discount = DiscountItems.FirstOrDefault(Function(di) di.SKU = ci.SKU) _
})
Solution 2
C#:
new {name1 = "value1", name2 = "value2"}
VB equivalent:
New With {Key .name1 = "value1", Key .name2 = "value2"}
Also,
C#:
new {anotherObj.prop1, anotherObj.prop2}
VB equivalent:
New With {Key anotherObj.prop1, Key anotherObj.prop2}
Note: The Key keyword in VB equivalents is necessary. When you specify the Key in VB, the property becomes read-only and is checked in Equal method AND in C# all properties of anonymous types are read-only and are checked in Equal method.
See:
Anonymous Types (C# Programming Guide)
Anonymous Types (Visual Basic)
Related videos on Youtube
Ben McCormack
Becoming a better version of myself. Website: http://benmccormack.com Twitter: @bmccormack I find great satisfaction in developing solutions that make it easier and simpler for people to do their jobs. I haven't updated by Stack Overflow CV in forever, so check out my LinkedIn page.
Updated on January 30, 2020Comments
-
Ben McCormack over 4 years
I'm trying to translate some C# LINQ code into VB.NET and am stuck on how to declare an anonymous type in VB.NET.
.Select(ci => new { CartItem = ci, Discount = DiscountItems.FirstOrDefault(di => di.SKU == ci.SKU) })
How do you translate C#'s
new { ... }
syntax into VB.NET? -
Pat Migliaccio almost 8 yearsThanks! Trying to write something so simple in VB is painstakingly hard when working regularly in C#.
-
Darryl over 5 yearsThe
Key
keyword is indeed required if you want the exact same behavior as C#. Just to clarify, VB gives you some flexibility with anonymous types that C# doesn't provide. Any fields you don't precede withKey
is read-write rather than read-only and is excluded from equality comparisons, which just might be exactly what you want.