views:

178

answers:

4

Hi, 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

+1  A: 

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.

Fiona Holder
A: 

Have you tried

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

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

Rob Fonseca-Ensor
Hi Rob, Do you have any sample code. I am quite new to Linq and trying to understand as much as I could.Thanks
sorry, there was a link hiding on my post: http://www.hookedonlinq.com/OuterJoinSample.ashx
Rob Fonseca-Ensor
A: 

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

List1.Concat(List2)
Jimmy