我想检查两个列表是否包含相同的项目。项目的顺序并不重要,相同的项目可能会在每个列表中出现两次。
例如:
var List1 = new List<int> { 1, 2, 2 };
var List2 = new List<int> { 2, 1, 2 };
//equal
var List1 = new List<int> { 1, 2, 2 };
var List2 = new List<int> { 2, 1, 1 };
//not equal - different quantities of 1s and 2s in the two lists
Run Code Online (Sandbox Code Playgroud)
目前我按如下方式执行此操作:
var List2copy = List2.ToList();
if (List1.Count != List2.Count) return false;
return List1.All(x => List2copy.Remove(x));
Run Code Online (Sandbox Code Playgroud)
然而现在我需要IEqualityComparer对这两个项目使用 an ,这是Remove不能接受的。谁能想到一个有效的解决方案来解决这个问题?IEnumerable如果它接受一个而不是一个,它也会很有用List
尝试一下这个应该适合您的情况:
return ListA.OrderBy(x => x).SequenceEqual(ListB.OrderBy(x => x));
Run Code Online (Sandbox Code Playgroud)
只是临时订单然后比较
| 归档时间: |
|
| 查看次数: |
667 次 |
| 最近记录: |