1

I work through a linq book and just do not understand why

customers.where(function(x) x.city = "London").Select(function(y) new with{y.CompanyName, y.Country})

works (creating an anonyomous type, I got that) but

customers.where(function(x) x.city = "London").select(function(y) y.countryname, y.country)

doesnt work. Isnt it possible to select multiple fields in a select query?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
ruedi
  • 5,365
  • 15
  • 52
  • 88

1 Answers1

5

The reason is: the second is not a valid syntax to create an anonymous type.

So this:

new with{y.CompanyName, y.Country} 

creates an anonymous type with two properties whereas this

y.countryname, y.countr 

does create nothing but a compiler error.

It would make sense if you'd create a class Company and provide a constructor like:

Public Class Company
    Public Sub New(companyName As String, countryName As String)
        Me.Country = countryName
        Me.Name = companyName
    End Sub

    Public Country As String
    Public Name As String
End Class

Now you can use this syntax to create an IEnumerable(Of Company):

Dim companies = customers.
    Where(Function(x) x.city = "London").
    Select(Function(x) New Company(x.CompanyName, x.Country))

or in query syntax (which i like more in VB):

Dim companies = From c In customers
                Where c.City = "London"
                Select New Company(c.CompanyName, c.Country)
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Hi Tim, this is very helpful for me and gives an hint to my all day long question how to handle anonymous types too. Thanks a lot! – ruedi Aug 21 '14 at 12:20