开发者

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 dup开发者_JS百科licates. 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


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

List1.Concat(List2)


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.


Have you tried

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜