vb.net 在 lambda 表达式中选择多个字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25425925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:05:08  来源:igfitidea点击:

Select multiple fields in lambda expression

vb.netlinq

提问by ruedi

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

我读了一本 linq 书,只是不明白为什么

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?

不起作用。是否可以在选择查询中选择多个字段?

回答by Tim Schmelter

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

创建一个具有两个属性的匿名类型,而 this

y.countryname, y.countr 

does create nothing but a compiler error.

除了编译器错误外,什么也不会产生。

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

如果您创建一个类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

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

现在您可以使用此语法创建一个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):

或查询语法(我更喜欢在 VB 中):

Dim companies = From c In customers
                Where c.City = "London"
                Select New Company(c.CompanyName, c.Country)