2

I'm trying to compare three lists and from these lists, trying to find the unique element.

As an example:

List A: 1 
List B: 1, 2
List C: 1, 2, 3

As a result, element "3" should be stored.

What I have attempted by looking at previous questions and expanding on is:

 Dim result1 As List(Of Long) = A.Except(B).ToList()
 Dim result2 As List(Of Long) = C.Except(result1).ToList()

The issue I face is my lists could be as such:

List A: 1
List B: 1
List C: 1, 2

As a result, result1 will store 0 which compares to list C and were then storing in result2: 1 and 2

Is it possible to compare three lists simultaneously? The except document on Microsoft states 2 lists only. Alternatively I could just do a pre check to see if A and B are the same and not to compare them but rather do a 3 way comparison.

Aiden
  • 151
  • 2
  • 12

2 Answers2

2

How about:

ListA
  .Concat(ListB)
  .Concat(ListC)
  .GroupBy(Function(i) i)
  .Where(Function(g) Not g.Skip(1).Any())
  .Select(Function(g) g.Key)
Magnus
  • 41,888
  • 7
  • 70
  • 108
  • Thanks Magnus. I've managed to get it building by putting your code on one line (VB doesn't recognise new lines unless you use _ ") Can't give it a vote up yet due to lack of points but ive given it the green tick! – Aiden Aug 30 '17 at 21:11
0

There are several ways to do this...

Dim listOfLists = new List(Of List(Of Long))()From { _
    listA, _
    listB, _
    listC _
}
Dim resultList = listOfLists.Aggregate(Function(previousList, nextList) previousList.Intersect(nextList).ToList())

Jon Skeet has another approach, see Intersection of multiple lists with IEnumerable.Intersect() (C#)

IronAces
  • 1,695
  • 1
  • 24
  • 31
  • I like your solutions better as its far easier to understand. Just having issues implementing it. I had to make a modification for both variables as they wanted an As clause so there like this now: Dim listOfLists As List(Of Long) = ... But im getting errors throughout the lines such as "overload resolution failed" due to too many operators – Aiden Aug 30 '17 at 15:35