【问题标题】:How to find common elements in several List(of)?如何在几个 List(of) 中找到共同的元素?
【发布时间】:2014-04-22 12:41:05
【问题描述】:

我有以下三个列表

Dim foodList1 As New List(Of Food)
Dim foodList2 As New List(Of Food)
Dim foodList3 As New List(Of Food)

Dim resualt = From c In db.Food
              Where c.Code = X
              Select c

m_FoodList1 = resualt.ToList

我需要创建一个新列表,其中包含这三个列表共有的食物。 有什么方法可以用来代替遍历列表和比较它们吗? 提前谢谢你

【问题讨论】:

标签: vb.net entity-framework linq list


【解决方案1】:

您可以为此目的使用Intersect() 方法。这适用于内部的 HashSet,因此它的性能非常好:

Dim result = foodList1.Intersect(foodList2).Intersect(foodList3)

如果 Food 类尚未覆盖 EqualsGetHashCode,您可以创建一个特殊的 IEqualityComparer 并将其作为参数提供给 Intersect

Class FoodEqualityComparer
    Implements IEqualityComparer(Of Food)

    Public Function Equals(x As Food, y As Food) As Boolean Implements IEqualityComparer(Of Food).Equals
        Return x.Code = y.Code
    End Function

    Public Function GetHashCode(x As Food) As Integer Implements IEqualityComparer(Of Food).GetHashCode
        Return x.Code.GetHashCode()
    End Function
End Class

' ...

Dim eqComp As New FoodEqualityComparer()
Dim result = foodList1.Intersect(foodList2, eqComp).Intersect(foodList3, eqComp)

【讨论】:

    【解决方案2】:

    试试这个:

    Dim resualt = From fl1 In foodList1
                  Join fl2 In fooldList2
                  On fl1.Code Equals fl2.Code
                  Join fl3 In foodList3
                  On fl1.Code Equals fl3.Code
                  Select fl1
    
    m_FoodList1 = resualt.ToList
    

    使用上述方式,您可以在三个列表之间建立连接。因此,您可以获得他们的常见食物。

    有关 linq 中连接的文档,请查看此处How to: Combine Data with LINQ by using Joins (Visual Basic)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多