c# - 将 Dictionary 的所有值移动到新键

标签 c# dictionary

我有一个通用字典,它为我的基于网格的游戏的 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/

相关文章:

c# - 带有签名证书的 WCF net.tcp

c# - 在类似于 String IndexOf() 的更大 byte[] 中寻找 byte[]?

值设置为列表的 Python 字典行为异常

node.js - NextJS - 如何在循环内的图像链接中添加参数

python - 不明白这个字典在迭代错误期间改变了大小

c++ - 多重映射如何在内部处理重复键?

c# - 为什么我们需要太多执行相同功能的方法?

c# - 对在 C# 中从 IntPtr 访问元素感到困惑

ios - 删除字典中的特定重复项

c# - 如何从循环外部访问变量?