Search code examples
c#listunique-values

get unique values from a list op points in c# error


I have a simple class point

public class point
{
    private double X;
    private double Y;
    public double x
    {
        get { return X; }
        set { X = value; }
    }
    public double y
    {
        get { return Y; }
        set { Y = value; }
    }
    public point() { }
    public point(double _x , double _y)
    {
        x = _x;
        y = _y;
    }
}

and I'm trying to use this loop to get unique values

        for (int i = 0; i < dim.Count; i++)
        {
            if (dimO[i].x == dim[i].x && dimO[i].y == dim[i].y)
            {
                continue;
            }
            else
            {
                dimO.Add(dim[i]);

            }
        }

but I got an " out of index" exception .. what's wrong here?


Solution

  • You should override Equals and GetHashCode if you want to compare a point by its x and y.

    public override bool Equals(object obj)
    {
        var point2 = obj as Point;
        return point2 != null && point2.x == x && point2.y == y;
    }
    
    public override int GetHashCode()
    {
       unchecked // Overflow is fine, just wrap
       {
           int hash = 17;
           // Suitable nullity checks etc, of course :)
           hash = hash * 23 + X.GetHashCode();
           hash = hash * 23 + Y.GetHashCode();
           return hash;
       }
    }
    

    I take the hash code function here.

    Now you could have a list of unique points by using

    var dim0 = (new HashSet(dim)).ToList();
    
    // linq
    var dim0 = dim.Distinct().ToList(); 
    

    Or if you want to use for loop

    var dim0 = new List<Point>();
    foreach(var p in dim){
        if(!dim0.Contains(p)){
            dim0.Add(p);
        }
    }
    

    Your solution is not working because dim0 does not initially have any point.