Linq(Visual Basic) - 比较两个匿名类型不会产生任何结果

时间:2015-03-18 14:09:47

标签: vb.net linq

我正在尝试使用复合键编写linq查询。以下是完整查询:

    Dim qeRelationships = From p In qualificationElements _
                          Join r In relationships On New With {.ElementCode = r.Parent, .Type = r.ParentType} _
                                              Equals New With {.ElementCode = p.ElementCode, .Type = p.Type} _
                          Join c In qualificationElements On New With {.ElementCode = r.Child, .Type = r.ChildType} _
                                                      Equals New With {.ElementCode = c.ElementCode, .Type = c.Type} _
                          Select New QualificationElementRelationship _
                                 With {.Parent = p, _
                                       .Child = c, _
                                       .Relationship = r.RelationshipType, _
                                       .Scope = r.Scope}

这没有结果,我不知道为什么。

我把它归结为两个例子。以下工作并返回记录:

    Dim qeRelationships = From p In qualificationElements _
                          Join r In relationships On r.Child Equals p.ElementCode _
                          Select New _
                                 With {.Relationship = r.RelationshipType, _
                                       .Scope = r.Scope}

此下一个代码段不起作用且不会返回记录

    Dim qeRelationships = From p In qualificationElements _
                          Join r In relationships On New With {.a = r.Child} Equals New With {.a = p.ElementCode} _
                          Select New _
                                 With {.Relationship = r.RelationshipType, _
                                       .Scope = r.Scope}

为什么第一个查询有效,第二个查询失败?

1 个答案:

答案 0 :(得分:0)

这是一个快速的帖子和答案!这是因为您的匿名类的所有属性都需要使用" Key"来标记。指令。

    Dim qeRelationships = From p In qualificationElements _
                          Join r In relationships On New With {Key .a = r.Child} Equals New With {Key .a = p.ElementCode} _
                          Select New _
                                 With {.Relationship = r.RelationshipType, _
                                       .Scope = r.Scope}

完整查询

    Dim qeRelationships = From p In qualificationElements _
                          Join r In relationships On New With {Key .ElementCode = r.Parent, Key .Type = r.ParentType} _
                                              Equals New With {Key .ElementCode = p.ElementCode, Key .Type = p.Type} _
                          Join c In qualificationElements On New With {Key .ElementCode = r.Child, Key .Type = r.ChildType} _
                                                      Equals New With {Key .ElementCode = c.ElementCode, Key .Type = c.Type} _
                          Select New QualificationElementRelationship _
                                 With {.Parent = p, _
                                       .Child = c, _
                                       .Relationship = r.RelationshipType, _
                                       .Scope = r.Scope}