简体   繁体   English

如何在多个列表中查找像整数

[英]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) 在vb.net应用程序中,我有一组当前存储在多个Arraylist中的整数(但是如果需要的话,可能有所不同)

al1 = {1, 2, 3, 6, 7, 9} al2 = {2, 3, 4, 9} al3 = {2, 3, 19} 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} 我想拿一套{2,3}

I thought about using LINQ to join the list, but the number of Arraylist can change. 我考虑过使用LINQ来加入列表,但是Arraylist的数量可以改变。 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. 您可以为此使用Enumerable.Intersect方法。 And change your ArrayList to a List(Of T) . 并将您的ArrayList更改为List(Of T) That makes it easier to use LINQ methods. 这使得使用LINQ方法更加容易。

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: 要补充史蒂文的答案:如果您不能将ArrayList对象更改为List(Of Integer)对象,则仍然可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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