How to find like integers in multiple list
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 开发者_Python百科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?
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)
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)())
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.
精彩评论