简体   繁体   English

比较两个列表,使它们在元素中相等

[英]Compare two lists to make them equal in elements

I have two lists named List1 & List2. 我有两个名为List1和List2的列表。

Now say List1 & List2 has 5 elements {a,b,c,d,e}. 现在说List1和List2有5个元素{a,b,c,d,e}。 Now if I remove {b,c} from List1 and add {f,g,h} to List1, how can i make List2 Equal(by doing add & remove operation on it.). 现在,如果我从List1中删除{b,c}并将{f,g,h}添加到List1,我如何使List2相等(通过对其执行添加和删除操作)。

"(by doing add & remove operation on it.)" “(通过对其进行添加和删除操作。)”

Why this constraint? 为什么这个约束?
The easiest, most reliable and probably the fastest way: 最简单,最可靠,最快捷的方式:

List2 = List1.ToList();

But if you really want it: 但如果你真的想要它:

List2.RemoveRange(List2.Except(List1));  // You may have to write RemoveRange()
List2.AddRange(List1.Except(List2));

Let the List2 be just a reference of List1, for example: 让List2只是List1的引用,例如:

List<string> list1 = new List<string>();
List<string> list2 = list1;

Modifying the list1 will affect the list2 as well 修改list1也会影响list2

The @Henk Holterman suggests the right way(on the first part of the answer), but if you want exactly what you mentioned in OP then you can use this @Henk Holterman建议正确的方法(在答案的第一部分),但如果你想要你在OP中提到的那么你可以使用这个

list2.RemoveAll(l => !list1.Contains(l));
list2.AddRange(list1.Except(list2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM