Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 502
Ben McCormack Avatar asked Jun 29 '10 15:06

Ben McCormack


People also ask

What is anonymous type in LINQ?

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.

Do anonymous types work with LINQ?

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.

What is LINQ VB?

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.

How do you define anonymous type?

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.


1 Answers

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) _ }) 
like image 97
Justin Niessner Avatar answered Oct 05 '22 16:10

Justin Niessner