处理 C# 中具有重复项的列表的并集
我试图了解如何处理可能有重复项的两个列表的并集或合并。 例如,List1 具有 { A, B, C},List2 具有 { B, C, D }。 我尝试使用 Union 操作并获得一个包含值 (A、B、C、D} 的新列表。但是,我需要第二个列表中的 B 和 C 值,而不是第一个列表。 有没有办法指定联合方法,使用哪个重复值。
我现在使用的代码是
var newList = List1.Union<Object>(List2).ToList();
感谢您的帮助。 贾维德
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
并集在逻辑上是一个集合运算。 Concat 就是您要寻找的。
Union is logically a set operation. Concat is what you're looking for.
你可以这样做吗:
..因为反转它们可能会给你带来你需要的东西?
编辑:
这显然不起作用。抱歉,我没有测试过,这只是对问题的第一反应。
怎么样,使用上面的相反表示法,然后调用 List.Sort() 将它们恢复到您想要的顺序?它假设您有一个属性可供排序,但如果有人没有提出更优雅的解决方案,您甚至可以人为地创建一个属性。
Could you just do:
.. 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
您可以查看
加入
您的列表。在该操作之后,您将拥有每个重复项的“连接”对象以进行检查......you could look at
Join
ing your lists instead. After that operation you'd have the "join" objects for each duplicate to inspect...