问题描述
public class ExecutionMap
{
protected SortedDictionary<object,object> ExecutionMap { get; set; }
}
假设我可以说我在该地图中有一个对象,我想将其位置与下一个交换:
public void SwapUp(object key)
{
value = ExecutionMap.Get(key);
//How do I do I swap with the one that comes before it
}
将它与之前的交换的有效方法是什么? 我宁愿不必枚举字典来找到它之前的键
解决方法
您可以使用第三方 C5 库中的 SortedDictionary<K,V>
代替 C5.TreeDictionary<K,V>
。这种类型提供了关于查找上一个和下一个条目、查找条目范围、支持向后枚举等的丰富功能。所有这些操作都是在红黑树集之上有效实现的。相比之下,原生 SortedDictionary<K,V>
提供的功能相当差,不足以实现您想要实现的目标。
public class ExecutionMap
{
protected C5.TreeDictionary<object,object> ExecutionMap { get; set; }
public void SwapUp(object key)
{
// Find the entry with this key
if (ExecutionMap.Find(ref key,out var value))
{
// Find the entry that comes before it
if (ExecutionMap.TryPredecessor(key,out var predecessor))
{
// Create a key that is smaller than the key of the predecessor
// Creating a suitable key may be tricky
var newKey = CreateSmallerKey(predecessor.Key);
// Swap the key of the stored value
// An exception will be thrown if the newKey already exists
ExecutionMap.Add(newKey,value);
bool removed = ExecutionMap.Remove(key);
Debug.Assert(removed);
}
}
}
}