SortedSet类中的所有单元,都是排好序的,一些时候会非常好用
//首先定义自己需要排序的类
public class cell
{
public int x;
public int y;
public int fcost;
public override string ToString()
{
return $"{x},{y},{fcost}";
}
}
//然后写一个类定义排序规则
public class ComparerCell : IComparer<cell>
{
public int Compare(cell x, cell y)
{
int offset = x.fcost - y.fcost;
if (offset == 0)
{
return (x.x * 1000 + x.y) - (y.x * 1000 + y.y);
}
return offset;
}
}
public class Test
{
public void Run()
{
//初始化SortedSet
ComparerCell cc = new ComparerCell();
SortedSet<cell> sortCells = new SortedSet<cell>(cc);
for (int i = 0; i < 100; i++)
{
cell c = new cell();
c.x = i;
c.y = i;
c.fcost = 10;
//添加的时候需要注意,sortCells中如果排序规则中相等的两个对象
//会被视为相同的对象,不能重复添加
sortCells.Add(c);
}
//打印可以看到是按照从小到大排列好了
foreach (var item in sortCells)
{
Console.WriteLine(item);
}
//另外还需要注意的一点,如果已经添加进去的对象,就不要修改与排序相关的值了,
//如果修改了,该对象在SortedSet中的顺序并不会改变,并且移除的时候会出现异常
}
}