JimmyJimm - 5 months ago 23

Vb.net Question

I have two lists of integers. I would like to get numbers from one list which are not in the second list and put the result to another list. If there is no difference the resulting list will be empty. What is the best way to do so?

Example:

`first List(Of Integer)`

4

5

6

7

secondList List(Of Integer)

6

7

resultList List(Of Integer)

4

5

Answer

Using the IEnumerable extension Except

```
Dim l1 = New List(Of Integer) From {4, 5, 6, 7}
Dim l2 = New List(Of Integer) From { 6, 7}
Dim l3 = l1.Except(l2).ToList() ' result is {4,5}
```

This will follow your requirement of all numbers not in the second list, but pay attention that this will not give you a list of unique numbers between the two lists. If you want an union of the two lists then the extension to use is

```
Dim l1 = New List(Of Integer) From {4, 5, 6, 7, 2}
Dim l2 = New List(Of Integer) From { 3, 6, 7}
Dim l3 = l1.Union(l2).ToList() ' result is {4,5,6,7,3}
```

Finally, if you want the numbers that are in both lists then you use Intersect

```
Dim l1 = New List(Of Integer) From {4, 5, 6, 7}
Dim l2 = New List(Of Integer) From { 6, 7}
Dim l3 = l1.Intersect(l2).ToList() ' result is {6,7}
```