Check if two lists are equal [duplicate]
Solution 1:
Use SequenceEqual
to check for sequence equality because Equals
method checks for reference equality.
var a = ints1.SequenceEqual(ints2);
Or if you don't care about elements order use Enumerable.All
method:
var a = ints1.All(ints2.Contains);
The second version also requires another check for Count
because it would return true even if ints2
contains more elements than ints1
. So the more correct version would be something like this:
var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;
In order to check inequality just reverse the result of All
method:
var a = !ints1.All(ints2.Contains)
Solution 2:
List<T>
equality does not check them element-by-element. You can use LINQ's SequenceEqual
method for that:
var a = ints1.SequenceEqual(ints2);
To ignore order, use SetEquals
:
var a = new HashSet<int>(ints1).SetEquals(ints2);
This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:
var counts = ints1
.GroupBy(v => v)
.ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
int c;
if (counts.TryGetValue(n, out c)) {
counts[n] = c-1;
} else {
ok = false;
break;
}
}
var res = ok && counts.Values.All(c => c == 0);
Finally, if you are fine with an O(N*LogN)
solution, you can sort the two sequences, and compare them for equality using SequenceEqual
.
Solution 3:
Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement),
SecondList.OrderBy(sElement => sElement))