Linq查询耗时太长

时间:2016-04-27 11:44:57

标签: vb.net linq

请参阅以下代码:

 Dim listPersonExact As List(Of type1) = ISystem1.GetMatches(getExclusions()) '1    
        Dim checks = From t1 In listPersonExact _
            Join t2 In listCheckedMerges On t1.MasterID Equals t2.MasterID And t1.ChildID Equals t2.ChildID _
            Select New With {t1.MasterID, t1.ChildID, t1.MergeTypeID}
        Dim listCheckedMerges As List(Of type1) = ISystem1.GetMatches


        For Each var In checks
            MsgBox('Got here')
        Next

ForEach很快就达成了。但是,从For Each移动到消息框需要很长时间。有什么办法可以优化吗?

更新 继Tim Shmelters发表评论后,我将以下内容作为测试:

Public Shared Sub LinqTest()
        Dim t1 As New TestPerson
        t1.id = 1
        t1.name = "Ian"

        Dim t2 As New TestPerson
        t2.id = 2
        t2.name = "Lauren"

        Dim list As List(Of TestPerson) = New List(Of TestPerson)
        list.Add(t1)
        list.Add(t2)

        Dim list2 As List(Of TestPerson) = New List(Of TestPerson)
        list2.Add(t1)

        Dim test = From p1 In list Join p2 In list2 On New With {p1.id, p1.name} Equals New With {p2.id, p2.name} Where t1.id = t2.id And t1.name = t2.name Select p1.id, p1.name
        For Each var In test
            MsgBox(var.id)
            MsgBox(var.name)
        Next


    End Sub

我希望FOR循环循环一次,但它不会循环。这是为什么?

1 个答案:

答案 0 :(得分:1)

  

ForEach很快就达成了。但是,这需要很长时间   时间从For Each移动到消息框。

那是LINQ的deferred execution。查询本身只定义了它的执行方式。 For Each实际上会执行它。

但它根本不应该编译。您无法在加入条件中使用And如果要加入多个列/属性,请使用匿名类型。

根据这个提示你已经尝试过:

Dim test = From p1 In list Join p2 In list2 
           On New With {p1.id, p1.name} Equals New With {p2.id, p2.name} 
           Where t1.id = t2.id And t1.name = t2.name 
           Select p1.id, p1.name
  

我希望FOR循环循环一次,但它不会循环。   这是为什么?

在VB.NET中,您必须定义keys of an anonymous type(而不是C#,其中所有属性都是自动键)。否则只比较参考。

所以这应该有效(请注意,您的Where是多余的):

Dim test = From p1 In list Join p2 In list2 
           On New With {Key p1.id, Key p1.name} Equals New With {Key p2.id, Key p2.name}
           Select New With {Key p1.id, Key p1.name}