I want to check if two lists contain the same items. The order of the items doesn't matter, and the same items might appear twice in each list.
For example:
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
Currently I do this as follows:
var List2copy = List2.ToList();
if (List1.Count != List2.Count) return false;
return List1.All(x => List2copy.Remove(x));
Now however I need to use an IEqualityComparer
for the two items, which Remove
cannot accept. Can anyone think of an efficient solution for the problem? It would also be useful if it accepted an IEnumerable
rather than a List
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…