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

Steve Davies picture Steve Davies · Feb 9, 2009 · Viewed 41.2k times · Source

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.

Answer

Joel Coehoorn picture Joel Coehoorn · Feb 9, 2009

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.