How to compare two generic lists in C# 3.0? [duplicate]

大兔子大兔子 提交于 2019-12-02 08:29:25

If you want to compare regardless of element order, try the UnorderedEqual<T> method from here:

Otherwise:

var list1 = new List<int> { 1, 2, 3 };
var list2 = new List<int> { 1, 2, 3 };
var areSame = Enumerable.SequenceEqual(list1, list2);
Rohan West

Check out this answer, it provides a method that determines whether two sequences contain the same elements.

If you want to compare two sequences in .NET 3.5 and beyond (that's the version of the framework which C# 3.0 ships with), then you should use the SeqenceEqual extension method on the Enumerable class in the System.Linq namespace.

However, for this, it will use the default equality comparer for the type parameter T in the IEnumerable<T> implementations it is comparing.

If you want to change the way that equality is checked for, then you should pass an implementation of IEqualityComparer<T> to the SequenceEqual method to use when comparing the items from each sequence.

Also, if you are trying to see if two sets are equal (as represented by IEnumerable<T>) then your best bet is to check use the Except extension method on the Enumerable class and make sure that the result set doesn't have any entries, and that both IEnumerable<T> implementations have the same number of entries (since Except can return an empty sequence even with different length sequences passed to it) which you can do with the Count extension method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!