简体   繁体   中英

C# IComparable for X and Y co-ordinates

Suppose I have a List<Point> which stores a list of X and Y points, but I want these to be ordered. Suppose I do not know the domain of X and Y values in advance, so I'll use long which is large enough for my purposes.

At any given moment, the list can have a very large or very small amount of points, and these points are likely very sparsely distributed, but I need to be able to very efficiently retrieve and insert particular points if they exist in the list.

In the past, I've used IComparable<> and List.BinarySearch() with great success. Unfortunately, I need to be able to insert and retrieve based on both an X and Y value.

If I know the domain of X and Y in advance, and the domain is small enough, then I can just add the numbers together with one number raised to the next power of the domain of the other. This ensures no collisions and I can efficiently retrieve/insert values. For example, if X and Y are both between 0 and 9, then I can just compare on 10 * X + Y . Because all my data types are 64-bit integers, I can't really do this.

Without restricting the domain, is there any other way I can achieve this functionality?

One method that would definitely work would be to compare on X.ToString("N19") + Y.ToString("N19"), however this is now string comparison instead of numerical comparison and this would come with a huge performance penalty.

Edit: I need the "N19" because otherwise (X = 1234, Y = 5) would resolve to the same as (X = 1, Y = 2345); and all the other collisions in between.

Instead of combining multiple components of a vector into one scalar value for comparison you could just compare each component, eg

int CompareTo(Point p)
{
    if (this.X < p.X)
    {
        return -1;
    }
    else if (this.X > p.X)
    {
        return 1;
    }
    else
    {
        return this.Y.CompareTo(p.Y);
    }        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM