您最好使用HashSet或Dictionary(如果您需要将它们按特定顺序保存)以确保它们确实是唯一的。
然后你应该重写GetHashCode和Equals来检查相等性。
GetHashCode 的最佳实践:覆盖 System.Object.GetHashCode 的最佳算法是什么?
执行
public class Coordinate
{
public Int32 X { get; set; }
public Int32 Y { get; set; }
public override int GetHashCode()
{
Int32 hash = 17;
hash = hash * 23 + X;
hash = hash * 23 + Y;
return hash;
}
public override Boolean Equals(object obj)
{
Coordinate other = obj as Coordinate;
if (other != null)
{
return (other.X == X) && (other.Y == Y);
}
return false;
}
}
字典
Int32 count = 0;
Dictionary<Coordinate, Int32> cords = new Dictionary<Coordinate, Int32>();
// TODO : You need to check if the coordinate exists before adding it
cords.Add(new Coordinate() { X = 10, Y = 20 }, count++);
// To get the coordinates in the right order
var sortedOutput = cords.OrderBy(p => p.Value).Select(p => p.Key);
哈希集
HashSet<Coordinate> cords = new HashSet<Coordinate>();
cords.Add(new Coordinate() { X = 10, Y = 20 });