代码之家  ›  专栏  ›  技术社区  ›  Ben

Linq to Object-选择Distinct

  •  1
  • Ben  · 技术社区  · 14 年前

    我不太明白为什么这个LINQ语句不能像我预期的那样工作:

        Dim distinctSurchargesList = (From thisparent As Parent In ThisParentCollection _
                                        From thisChild As Child In thisparent.theseChildren _
                                        Select New With {.childId = thischild.Id}).Distinct()
    

    我假设这将创建一个新的匿名类型集合,这将是不同的。相反,它创建一个“thisParentCollection”大小的集合,其中包含重复的“MyAnonymousType”(重复的ID)。

    有人能告诉我哪里出了问题吗?

    谢谢

    1 回复  |  直到 14 年前
        1
  •  4
  •   Winston Smith    14 年前

    匿名类型集合将按引用值而不是按 childId 字段。每个匿名类型都有不同的对象引用,因此它们都是不同的。

    只需选择ID,不要将其投影到匿名类型中。