我不相信这SortedSet.IsSubsetOf
会按预期工作。给出这段代码,不应该ss.IsSubsetOf(l)
返回 True 吗?
我怀疑问题出在我的CompareTo
函数中,但我看不到问题所在。
我还添加了一个单独的循环,认为必须在other
IEnumerable 内找到该集合并进行排序。。。但这也行不通。
谁能解释为什么会发生这种行为?
List<Point> l = new();
SortedSet<Point> ss = new();
HashSet<Point> h = new();
for (int i = 0; i < 100; i++)
{
var p = new Point(i, i);
l.Add(p);
l.Add(p);
h.Add(p);
h.Add(p);
ss.Add(p);
ss.Add(p);
}
// additional loop to get a sorted set.
for (int i = 0; i < 100; i++)
{
l.Add(new Point(i, i));
}
Console.WriteLine(l.Count); // 300
Console.WriteLine(h.Count); // 100
Console.WriteLine(ss.Count); // 100
Console.WriteLine(h.IsSubsetOf(l)); // True (as expected)
Console.WriteLine(h.IsProperSubsetOf(l)); // False
// This is the line in question
Console.WriteLine(ss.IsSubsetOf(l)); // False ?????????
Console.WriteLine(ss.IsProperSubsetOf(l)); // False
readonly struct Point : IComparable<Point>, IEquatable<Point>
{
public Point(double x, double y)
{
X = x;
Y = y;
}
public double X { get; }
public double Y { get; }
public int CompareTo(Point other)
{
if (X == other.X)
{
return Y.CompareTo(other.Y);
}
else
{
return X.CompareTo(other.X);
}
}
public bool Equals(Point other)
{
return X == other.X && Y == other.Y;
}
public override int GetHashCode()
{
return HashCode.Combine(X, Y);
}
}