-2

I have 2 lists in C#

List<int> list1 = new List<int> { 78, 92, 100, 37, 81 };
List<int> list2 = new List<int> { 3, 92, 1, 37 };

The expected result should be

{ 3, 78, 100, 1, 81 }

Please note! Duplicates: 92 and 37 doesn't appear anymore in the new list. The new list should have non duplicated elements from both lists.

Each list cannot have duplicated values. Ideally i would like to extend it to an object.

I can do it iterating manually both lists finding and removing duplicates.

My question is : Is there a more elegant and compact way to do in with .NET C# ?

Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
Claudio Ferraro
  • 4,357
  • 6
  • 41
  • 69

5 Answers5

3

You are looking for SymmetricExceptWith or its emulation, e.g.

  HashSet<int> result = new HashSet<int>(list1);

  result.SymmetricExceptWith(list2);

Let's have a look at the items:

  Console.Write(string.Join(", ", result));

Outcome:

  78, 100, 81, 3, 1

If you want List<int> (not HashSet<int>) as a result, add ToList():

  List<int> final = result.ToList();      
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
1
var result = list1.Concat(list2).
             GroupBy((g) => g).Where(d => d.Count() == 1).
             Select(d => d.Key).ToList();
huMpty duMpty
  • 14,061
  • 13
  • 55
  • 93
1

If you intersect both lists then subtract it from their union you will get the result:

var result = list1
    .Concat(list2)
    .Except(list1.Intersect(list2))
    .ToList();
kara
  • 3,030
  • 4
  • 19
  • 31
DotNet Developer
  • 2,583
  • 1
  • 13
  • 21
0

You can use the Distinct() method from Linq, which, given a list containing duplicates, returns distinct elements from a sequence of integers. More on Distinct() here .

Xander
  • 57
  • 3
0
List<int> list1 = new List<int> { 78, 92, 100, 37, 81 };
List<int> list2 = new List<int> { 3, 92, 1, 37 };

IEnumerable<int> result = list1
    .Concat(list2)              // Concat both lists to one big list. Don't use Union! It drops the duplicated values!
    .GroupBy(g => g)            // group them by values
    .Where(g => g.Count() == 1) // only values which have a count of 1
    .Select(s => s.Key);        // select the values

Console.WriteLine(string.Join(", ", result));
kara
  • 3,030
  • 4
  • 19
  • 31