【发布时间】:2019-08-24 13:19:45
【问题描述】:
我正在尝试了解 LINQ Join 方法中这两个 Lambda 表达式之间的区别。
我看不懂的两行是Function(aaa) ...和Function(bbb) ...开头的那几行。
为什么我在第二个示例中为
aaa和bbb明确命名了字段Name,而在第一个示例中没有它也可以工作?
1234563
第一个示例(来自更改了变量名的 .Net Framework 文档):
Structure Person
Public Name As String
Public SecondName As String
End Structure
Structure Pet
Public Name As String
Public Owner As Person
End Structure
Dim magnus As New Person With {.Name = "Hedlund, Magnus"}
Dim terry As New Person With {.Name = "Adams, Terry"}
Dim charlotte As New Person With {.Name = "Weiss, Charlotte"}
Dim barley As New Pet With {.Name = "Barley", .Owner = terry}
Dim boots As New Pet With {.Name = "Boots", .Owner = terry}
Dim whiskers As New Pet With {.Name = "Whiskers", .Owner = charlotte}
Dim daisy As New Pet With {.Name = "Daisy", .Owner = magnus}
Dim people As New List(Of Person)(New Person() {magnus, terry, charlotte})
Dim pets As New List(Of Pet)(New Pet() {barley, boots, whiskers, daisy})
Dim query = people.Join(pets,
Function(aaa) aaa,
Function(bbb) bbb.Owner,
Function(ccc, ddd) _
New With {.OwnerName1 = ccc.Name, .Pet1 = ddd.Name})
第二个例子(我的代码)
Structure MyObject
Public Name As String
Public Value As Integer
End Structure
Dim Test1 As New List(Of MyObject) From {
New MyObject With {.Name = "a", .Value = 1},
New MyObject With {.Name = "b", .Value = 2},
New MyObject With {.Name = "c", .Value = 3}
}
Dim Test2 As New List(Of MyObject) From {
New MyObject With {.Name = "a", .Value = 11},
New MyObject With {.Name = "b", .Value = 22},
New MyObject With {.Name = "c", .Value = 33}
}
Dim Joined = Test1.Join(Test2,
Function(aaa) aaa.Name,
Function(bbb) bbb.Name,
Function(ccc, ddd) New With {
.Name1 = ccc.Name,
.Value1 = ccc.Value,
.Value2 = ddd.Value})
【问题讨论】: