user320587
user320587

Reputation: 1367

Handle Union of List in C# with duplicates

I am trying to understand how to handle union or merge of two lists that can have duplicates. For example, List1 has { A, B, C} and List2 has { B, C, D }. I tried to use the Union operation and got a new list with values (A, B, C, D}. However, I need the B & C values from the second list, not first one. Is there a way to specify the union method, which duplicate value to use.

The code I am using now is

var newList = List1.Union<Object>(List2).ToList();

Thanks for any help. Javid

Upvotes: 6

Views: 10779

Answers (4)

Jimmy
Jimmy

Reputation: 91472

Union is logically a set operation. Concat is what you're looking for.

List1.Concat(List2)

Upvotes: 7

Could you just do:

var newList = List2.Union<Object>(List1).ToList(); 

.. as reversing them will probably give you the ones you need?

EDIT:

That apparently doesn't work. Sorry, I didn't test it, it was just a first reaction to the problem.

How about, using the reversed notation above, but then calling List.Sort() to get them back in the order you want? It assumes that you have a property to order by, but you could even artifically create one if someone doesn't come up with a more elegant solution.

Upvotes: 2

Rob Fonseca-Ensor
Rob Fonseca-Ensor

Reputation: 15621

you could look at Joining your lists instead. After that operation you'd have the "join" objects for each duplicate to inspect...

Upvotes: 0

Aren
Aren

Reputation: 55946

Have you tried

var newList = List2.Union<Object>(List1).ToList();

Upvotes: 0

Related Questions