0

I have two list of A and B and trying to get elements from A which are not in B and from B which are not in A.

Below is my attempt to solve this.

var result = (List<string>)(from e in (A.Concat(B))
where !B.Contains(e) || !A.Contains(e)
select e);

And ran into below error..

Unable to cast object of type WhereEnumerableIterator1[System.String] to type System.Collections.Generic.List`1[System.String].

What can I try to solve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
BetterLateThanNever
  • 886
  • 1
  • 9
  • 31

2 Answers2

3

You can use Except:

List<int> firstList = new List<int> {1,2,3,4};

List<int> secondList = new List<int> { 1, 5 };

IEnumerable<int> res = secondList.Except(firstList).Concat(firstList.Except(secondList));

//Result => {5,2,3,4}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1

Regarding you cast error, the call should be like this.

var result = (from e in (A.Concat(B))
              where !B.Contains(e) || !A.Contains(e)
              select e).ToList();`

The ToList() method converts your LINQ query into a list.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
ShuberFu
  • 689
  • 3
  • 15