What is the best way to check two List lists for equality in C#

后端 未结 6 1770
误落风尘
误落风尘 2020-12-16 13:16

There are many ways to do this but I feel like I\'ve missed a function or something.

Obviously List == List will use Object.Equals() and re

6条回答
  •  天涯浪人
    2020-12-16 13:58

    Use linq SequenceEqual to check for sequence equality because Equals method checks for reference equality.

    bool isEqual = list1.SequenceEqual(list2);
    

    The SequenceEqual() method takes a second IEnumerable sequence as a parameter, and performs a comparison, element-by-element, with the target (first) sequence. If the two sequences contain the same number of elements, and each element in the first sequence is equal to the corresponding element in the second sequence (using the default equality comparer) then SequenceEqual() returns true. Otherwise, false is returned.

    Or if you don't care about elements order use Enumerable.All method:

    var isEqual = list1.All(list2.Contains);
    

    The second version also requires another check for Count because it would return true even if list2 contains more elements than list1.

提交回复
热议问题