Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c# - Compare two lists, where order doesn't matter, using IEqualityComparer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this should work for your situation:

return ListA.OrderBy(x => x).SequenceEqual(ListB.OrderBy(x => x));

Just a temporary order then compare


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...