如何在多个 List(of) 中找到共同元素?

3
我有三个列表,如下所示。
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

我需要创建一个新的列表,其中包含这三个列表所共有的食品。 除了逐个比较列表,还有没有其他方法可以使用? 谢谢您提前。


在列表中,食物是否保证是唯一的? - Luc Morin
请查看Intersect()方法 - Nico Schertler
2个回答

3
你可以使用Intersect()方法实现此目的。该方法在内部使用HashSet,因此性能非常好:
Dim result = foodList1.Intersect(foodList2).Intersect(foodList3)

如果Food类还没有覆盖Equals和GetHashCode方法,您可以创建一个特殊的IEqualityComparer并将其作为参数提供给Intersect方法:

如果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)

1

Try this one:

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中连接的文档,请参阅此处如何使用连接(Visual Basic)在LINQ中组合数据

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接