-3

I have 2 lists say list1 and list2. Like

 List<int> list1 = {1,2,3};
 List<int> list2 = {3,4};

now I want my resultant list to be like

{1,2,3,4}

I have tried this

result= list1.Union(list2).ToList();

But it gives result like

{1,2,3,3,4}

Can anyone help me with this?

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
Bits_Please
  • 546
  • 1
  • 5
  • 13
  • Please post a [mcve], I cannot reproduce the behavior you're describing, what you're describing is the result of calling `.Concat`, not `.Union`, the behavior of `.Union` is exactly what you say you want. As such, you must post a [mcve] so that we can see exactly what you're doing. – Lasse V. Karlsen Feb 02 '17 at 07:42
  • Possible you have lists of objects that do not implement `IComparable` – Gene R Feb 02 '17 at 07:45
  • 1
    Your code returned `{1,2,3,4}` when I tested it. Is it really what you are doing? – Guy Feb 02 '17 at 07:45
  • 1
    Please bear in mind that if you're not *actually* comparing numbers, but your own types, you must override `GetHashCode` and `Equals` in order for `.Union` to know how to compare your types. However, in the specific example you've posted, the code already does what you want it to do. – Lasse V. Karlsen Feb 02 '17 at 07:46

1 Answers1

2

It's simple:

var result= list1.Union(list2).Distinct().ToList();
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49