Thorin Oakenshield
Thorin Oakenshield

Reputation: 14662

How to get the difference of two list in C# using LINQ

I've two lists like

List<String> LISTONE=new List<String>() 

and

List<String> LISTTWO=new List<String>() 

and which contains

LISTONE   "A"
          "B"
          "C"
LISTTWO   "A"
          "D"
          "E"

and the required out put is

LISTTEMP  "B"   
          "C"
          "D"
          "E"

is there any way to do this using LINQ

Upvotes: 1

Views: 4409

Answers (3)

spender
spender

Reputation: 120400

LISTONE.Except(LISTTWO).Union(LISTTWO.Except(LISTONE)) //.Distinct()?

EDIT: The Union method implements Distinct behaviour, so Distinct would be redundant.

Upvotes: 2

Jamiec
Jamiec

Reputation: 136094

Assuming you want "All elements which do not appear in both lists", in which case, as my note above mentions, "B" should also be in there. this is the linq'ed answer.

one.Concat(two).Except(one.Intersect(two))

Upvotes: 2

Elisha
Elisha

Reputation: 23770

It can be done using Except() and Concat() LINQ methods:

LISTONE.Except(LISTTWO).Concat(LISTTWO.Except(LISTONE))

Upvotes: 5

Related Questions