views:

55

answers:

3

In a vb.net application I have a set of integers currently stored in multiple Arraylist (But this could be something different if required)

al1 = {1, 2, 3, 6, 7, 9} al2 = {2, 3, 4, 9} al3 = {2, 3, 19}

I would like to get the set {2, 3}

I thought about using LINQ to join the list, but the number of Arraylist can change. Im open to any ideas. I know I can always loop through everything and check if an integer exsist and keep track of it, but I thought there might be an easier way?

A: 

If you already have code that gives the common items of two lists, it's easy to extend that into any number of lists:

  • Get a list of common items of the first two lists.
  • Then get the common items of this result list and the third source list,
  • Then the common items of the new result list and the fourth source list
  • etc.
Hans Kesting
Hee Hans. 't Wordt tijd dat je LINQ gaat leren, je antwoord is veel te generiek ;-) Trouwens, ik miste jullie dit jaar op de DevDays.
Steven
Hoi Steven, ik had het expres generiek gehouden, het klonk nogal als huiswerk. En inderdaad, we waren er niet. Volgende keer beter.
Hans Kesting
+2  A: 

You can use the Enumerable.Intersect method for this. And change your ArrayList to a List(Of T). That makes it easier to use LINQ methods.

Dim set = al1.Intersect(al2).Intersect(al3)
Steven
That's exactally what I was hoping to find, thanks!
Travis Gneiting
+1  A: 

To add to Steven's answer: if you can't change your ArrayList objects to List(Of Integer) objects, you can still do this:

Dim set = al1.OfType(Of Integer)() _
    .Intersect(al2.OfType(Of Integer)()) _
    .Intersect(al3.OfType(Of Integer)())
Dan Tao