When working with distinct we should come to terms how to compare items (by default .net compares references, and that's why new[] {1, 2, 3} != new int[] {1, 2, 3}
since arrays' don't share the same reference).
We can do it while implementing IEqualityComparer<T>
for this, e.g.
public sealed class EnumerableEqualityComparer<T>
: IEqualityComparer<IEnumerable<T>> {
public bool Equals(IEnumerable<T>? x, IEnumerable<T>? y) {
if (ReferenceEquals(x, y))
return true;
if (ReferenceEquals(null, x) || ReferenceEquals(null, y))
return false;
return x.SequenceEqual(y);
}
public int GetHashCode(IEnumerable<T> obj) {
if (obj is null)
return -1;
if (obj is ICollection<T> c)
return c.Count;
// Count() without restriction - Take(10) - can be expensive
return obj.Take(10).Count();
}
}
and then use it within Distinct
:
var result = list
.Distinct(new EnumerableEqualityComparer<int>())
.ToList(); // let's have a list of the distinct arrays