Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling .Distinct() on enumerables of enumerables

Tags:

c#

linq

At the end of my current LINQ query, I have data which is in the form of an IEnumerable<IEnumerable<int>>, with several duplicate combinations.

For example:

{
  {5, 20}
  {5, 20}
  {10, 15}
}

What's the best way to filter these so that each set is only represented once? A LINQ answer would be ideal so I can chain it further.

like image 559
Bobson Avatar asked Oct 20 '25 11:10

Bobson


1 Answers

If you create a sequence equality comparer like this:

class SequenceEqualityComparer<T> : IEqualityComparer<IEnumerable<T>> {
    public bool Equals(IEnumerable<T> a, IEnumerable<T> b) {
        if (a == null) return b == null;
        if (b == null) return false;
        return a.SequenceEqual(b);
    }

    public int GetHashCode(IEnumerable<T> val) {
        return val.Where(v => v != null)
                .Aggregate(0, (h, v) => h ^ v.GetHashCode());
    }
}

Then, you can call .Distinct(new SequenceEqualityComparer<int>()).

like image 61
recursive Avatar answered Oct 23 '25 00:10

recursive