0

Here is the following issue I am trying to solve. Finding the set of distinct element from the following sequence:

var l = new List<double>() { 0, 0 + 1e-7, 1 - 1e-7, 1 };

In my case I consider that two values are equals if:

public class DistanceComparer : IEqualityComparer<double>
{
    public static IEqualityComparer<double> Default { get; } = new DistanceComparer();

    public bool Equals(double x, double y)
    {
        return Math.Abs(x - y) < 1e-6;
    }

    public int GetHashCode(double obj) => throw new NotImplementedException();
}

Is there a way for me to re-use LINQ or any other existing framework to compute the list of distinct values ?

malat
  • 12,152
  • 13
  • 89
  • 158
  • 1
    If you implement `GetHashCode` in some way (even just `=> 0`), then you can use LINQ `l.Distinct(DistanceComparer.Default)`. – Evk Sep 24 '21 at 08:23
  • 2
    That's not a correct implementation of `IEqualityComparer`. For one, `Equals` is not transitive. Had you implemented it correctly, passing it to `Distinct` should work. – Sweeper Sep 24 '21 at 08:24
  • @sweeper so I guess this answers the question :) – malat Sep 24 '21 at 08:26
  • 2
    https://stackoverflow.com/questions/51507022/iequatablepoint3d-within-a-tolerance-how-to-implement-gethashcode/51507334#51507334 – TheGeneral Sep 24 '21 at 08:30
  • @Sweeper it seems not possible to implement it correctly for this use case. – Evk Sep 24 '21 at 08:33
  • That community bot is a bit hammery, I wonder what the rules are it uses – TheGeneral Sep 24 '21 at 08:38
  • 2
    @TheGeneral it just means OP himself marked question as duplicate, so community bot closed it. – Evk Sep 24 '21 at 08:43
  • @Evk ahh yup thanks, you learn something new every day – TheGeneral Sep 24 '21 at 08:45

0 Answers0