Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "New ... With" syntax do in VB Linq?

What (if any) is the difference between the results of the following two versions of this VB Linq query?

' assume we have an XElement containing employee details defined somewhere else

Dim ee = From e In someXML.<Employee> _
Select New With {.Surname = e.<Surname>, .Forename = e.<Forename>}

and

Dim ee = From e In someXML.<Employee> _
Select Surname = .Surname = e.<Surname>, .Forename = e.<Forename>

ie what is the point of the New ... With syntax?

I suspect that this has a simple answer, but I can't find it - any links to suitable tutorials or Microsoft documentation would be appreciated.

like image 518
Steve Davies Avatar asked Feb 09 '09 15:02

Steve Davies


People also ask

Which option supports LINQ queries?

To use this example, you must set Option Infer to On . Local type inference also makes it possible to create anonymous types, which are described later in this section and are necessary for LINQ queries. In the following LINQ example, type inference occurs if Option Infer is either On or Off .

Does VB have Linq?

Visual Basic includes the following LINQ providers. The LINQ to Objects provider enables you to query in-memory collections and arrays. If an object supports either the IEnumerable or IEnumerable<T> interface, the LINQ to Objects provider enables you to query it.


2 Answers

The difference is that the 1st explicitly creates an anonymous type. The 2nd is a query expression, and may use an existing type rather than creating an anonymous type. From the documentation linked by Cameron MacFarland:

Query expressions do not always require the creation of anonymous types. When possible, they use an existing type to hold the column data. This occurs when the query returns either whole records from the data source, or only one field from each record.

like image 139
Joel Coehoorn Avatar answered Oct 11 '22 04:10

Joel Coehoorn


My understanding is that there is no difference.

New With is aimed to out-of-query usage like

Dim X = New With { .Surname = "A", .Forename = "B" }

Specifically for Linq queries, you can skip New With, but it is still useful for other situations. I am not sure, however, since I do not know VB 9 :)

like image 25
Andrey Shchekin Avatar answered Oct 11 '22 02:10

Andrey Shchekin