【问题标题】:Difference between two Lamba Expressions in LINQLINQ 中两个 Lambda 表达式的区别
【发布时间】:2019-08-24 13:19:45
【问题描述】:

我正在尝试了解 LINQ Join 方法中这两个 Lambda 表达式之间的区别。

我看不懂的两行是Function(aaa) ...Function(bbb) ...开头的那几行。

  1. 为什么我在第二个示例中为aaabbb明确命名了字段Name,而在第一个示例中没有它也可以工作?

  2. 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})

【问题讨论】:

    标签: vb.net linq lambda


    【解决方案1】:

    如果您查看documentation,您会发现第一个函数是外部序列的选择器,第二个函数是内部序列的选择器。

    内部和外部选择器的值必须具有相同的类型 (TKey),并且将使用该类型的默认比较器进行比较(有一个 overload 允许您传递比较器)。

    第三个函数是结果选择器,它接收一个TOuter 和一个TInner 实例,根据所选键匹配并返回一个TResult 值。

    所以,在第一个示例中,TKeyPersonouterSelectorinnerSelector 必须返回 Person,因此 aaabbb

    在第二个示例中,您选择比较 Name 字段而不是整个 MyObject 结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多