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?

3
  • 2
    Easy: because the second is not a valid syntax to create an anonymous type. Commented Aug 21, 2014 at 12:07
  • Is it possible to get a 'concrete' type out of it? Commented Aug 21, 2014 at 12:12
  • Yes, i've shown a way below in my answer. Commented Aug 21, 2014 at 12:13

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.