User1162527
User1162527

Reputation: 197

How to find common elements in several List(of)?

I have three lists as follow

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

I need to create a new list containing the foods that these three lists have in common. Is there any method that I can use instead of going through lists and comparing them ? Thank you in advance

Upvotes: 3

Views: 3977

Answers (2)

Markus
Markus

Reputation: 22511

You can use the Intersect() method for this purpose. This works on a HashSet internally so its performance is very good:

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

If the Food class does not override Equals and GetHashCode yet, you can create a special IEqualityComparer and supply it as a parameter to 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)

Upvotes: 3

Christos
Christos

Reputation: 53958

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

Using the above way, you make a join between the three lists. Hence you get their common foods.

For documentation of joins in linq please take a look here How to: Combine Data with LINQ by using Joins (Visual Basic).

Upvotes: 1

Related Questions