我通过一本linq书,只是不明白为什么
customers.where(function(x) x.city = "London").Select(function(y) new with{y.CompanyName, y.Country})
工作(创建一个anonyomous类型,我得到了),但
customers.where(function(x) x.city = "London").select(function(y) y.countryname, y.country)
不起作用。是否可以在选择查询中选择多个字段?
答案 0 :(得分:2)
原因是:第二个不是创建匿名类型的有效语法。
所以这个:
new with{y.CompanyName, y.Country}
创建一个具有两个属性的匿名类型,而这个
y.countryname, y.countr
除了编译器错误外什么都不做。
如果您创建一个类Company
并提供如下构造函数,那将是有意义的:
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
现在您可以使用此语法创建IEnumerable(Of Company)
:
Dim companies = customers.
Where(Function(x) x.city = "London").
Select(Function(x) New Company(x.CompanyName, x.Country))
或查询语法(which i like more in VB):
Dim companies = From c In customers
Where c.City = "London"
Select New Company(c.CompanyName, c.Country)