我有一个通用字典,它为我的基于网格的游戏的 map 中的每个坐标存储一个 Tile 定义。
Dictionary<IntVector2, Tile> tiles;
map 可以使用此设置任意调整大小,因为可以添加新坐标而无需更改任何其他内容。但是,我想使用 (0,0) 坐标作为其他计算的 map 轴心,这要求我能够在创建 map 后更改 map 中心坐标。
是否有更简洁、更高效的方法将字典中的所有值 (Tile) 移动到新坐标,必要时创建新键并随后删除所有未使用的键?
到目前为止我有这个:
public void MovePivot(int xDelta, int yDelta)
{
// Copy my existing tile map.
Dictionary<IntVector2, Tile> tilesCopy = new Dictionary<IntVector2, Tile>(tiles);
// Initialize a new empty one.
tiles = new Dictionary<IntVector2, Tile>();
// Copy all old values into the new one, but shift each coordinate.
foreach (var tile in tilesCopy)
{
IntVector2 newKey = tile.Key + new IntVector2(xDelta, yDelta);
tiles.Add(newKey, tile.Value);
}
}
这是否可以在不复制我的词典的情况下“就地”进行?
最佳答案
可以实现一种新的字典类型,它保留当前移位的内存并在读/写期间执行移位。
示例用法:
AdjustableDictionary<int, string> map = new AdjustableDictionary<int, string>((key, adj) => key + adj);
这应该很接近。值与引用类型之间可能存在问题。
public class AdjustableDictionary<K, V>
{
public K CurrentAdjustment { get; set; }
public int Count { get { return _dictionary.Count; } }
public ICollection<K> Keys { get { return _dictionary.Keys.Select(k => AdjustKey(k)).ToList(); } }
private IDictionary<K, V> _dictionary;
private Func<K, K, K> _adjustKey;
public AdjustableDictionary(Func<K, K, K> keyAdjuster = null)
{
_dictionary = new Dictionary<K, V>();
_adjustKey = keyAdjuster;
}
public void Add(K key, V value)
{
_dictionary.Add(AdjustKey(key), value);
}
public bool ContainsKey(K key)
{
return _dictionary.ContainsKey(AdjustKey(key));
}
public bool Remove(K key)
{
return _dictionary.Remove(AdjustKey(key));
}
public bool TryGetValue(K key, out V value)
{
return _dictionary.TryGetValue(AdjustKey(key), out value);
}
public ICollection<V> Values { get { return _dictionary.Values; } }
public V this[K key] {
get {
return _dictionary[AdjustKey(key)];
}
set {
_dictionary[AdjustKey(key)] = value;
}
}
public void Clear()
{
_dictionary.Clear();
}
private K AdjustKey(K key)
{
return _adjustKey != null
? _adjustKey(key, CurrentAdjustment)
: key;
}
}
上面的代码大部分是从这个 VirtualDictionary answer 修改而来的
关于c# - 将 Dictionary 的所有值移动到新键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38317204/