What's the equivalent VB.NET syntax for anonymous types in a LINQ statement?

Ben McCormack picture Ben McCormack · Jun 29, 2010 · Viewed 17.7k times · Source

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?

Answer

Justin Niessner picture Justin Niessner · Jun 29, 2010

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) _
})