简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM