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?
Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ in C#. Anonymous types contain one or more public read-only properties.
You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
LINQ enables you to query data from a SQL Server database, XML, in-memory arrays and collections, ADO.NET datasets, or any other remote or local data source that supports LINQ. You can do all this with common Visual Basic language elements.
Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.
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) _ })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With