简体   繁体   English

C#IComparable对于X和Y坐标

[英]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. 假设我有一个List<Point> ,它存储X和Y点的列表,但是我希望对它们进行排序。 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. 假设我事先不知道X和Y值的域,所以我将使用足够大的long来满足我的目的。

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. 过去,我曾成功使用IComparable<>List.BinarySearch() Unfortunately, I need to be able to insert and retrieve based on both an X and Y value. 不幸的是,我需要能够插入,并根据双方的X和Y值获取。

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. 如果我事先知道X和Y的域,并且该域足够小,那么我可以将数字与一个数字加到另一个数字的下一个幂上。 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 . 例如,如果X和Y都在0到9之间,那么我可以在10 * X + Y上进行比较。 Because all my data types are 64-bit integers, I can't really do this. 因为我所有的数据类型都是64位整数,所以我不能真正做到这一点。

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. 绝对可行的一种方法是在X.ToString(“ N19”)+ Y.ToString(“ N19”)上进行比较,但是现在这是字符串比较,而不是数值比较,这会带来巨大的性能损失。

Edit: I need the "N19" because otherwise (X = 1234, Y = 5) would resolve to the same as (X = 1, Y = 2345); 编辑:我需要“ N19”,因为否则(X = 1234,Y = 5)将解析为与(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);
    }        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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