如何找到几个List(of)中的常用元素?

时间:2014-03-17 10:40:53

标签: vb.net entity-framework linq list

我有三个列表如下

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

我需要创建一个新列表,其中包含这三个列表共有的食物。 是否有任何方法可以使用而不是通过列表并比较它们? 提前谢谢

2 个答案:

答案 0 :(得分:3)

您可以使用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)

答案 1 :(得分:1)

试试这个:

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)