假设我有一个排序字典,它的键被反对
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
}有什么有效的方法来交换这个和之前的那个呢?我不希望在查找关键字之前必须枚举字典。
发布于 2021-03-03 17:50:27
您可以使用第三方C5库中的C5.TreeDictionary<K,V>,而不是SortedDictionary<K,V>。这种类型提供了丰富的功能,包括查找前一个和下一个条目、查找条目范围、支持向后枚举等。所有这些操作都是在红黑树集合的顶部高效实现的。相比之下,原生SortedDictionary提供的功能相当差,并且不足以实现您试图实现的目标。
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);
}
}
}
}https://stackoverflow.com/questions/66449542
复制相似问题