开发者

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

开发者 https://www.devze.com 2022-12-20 02:00 出处:网络
This question a开发者_Go百科lready has answers here: Closed 12 years ago. Possible Duplicate: Is there a built-in method to compare collections in C#?
This question a开发者_Go百科lready has answers here: Closed 12 years ago.

Possible Duplicate:

Is there a built-in method to compare collections in C#?

What is the best way to compare to generic two generic lists in C# 3.0?


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

  • C# List Element Equality

Otherwise:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号