【问题标题】:Make a change in vocabulary's keys改变词汇的键
【发布时间】:2014-01-27 15:34:29
【问题描述】:

假设我有一个词汇

public Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();

键 - 1, ..., n

现在我想删除假设第 5 个元素,但想保持正常计数。

有 1, 2, 3, 4, 5, 6, 7, 8, 9.... 而不是 1, 2, 4, 6, 7, 8, 9, ....

怎么做?

【问题讨论】:

  • 你不能只用一个列表来代替吗?索引将“保持正常计数”
  • 在这里使用Dictionary 并不是很好,因为它不会阻止任何订单。你应该看看SortedList&lt;T&gt;
  • 我自己传递索引。
  • 当然可以,但我需要自己传递密钥

标签: c# loops dictionary iterator


【解决方案1】:

你可以定义这个实用方法:

public static IDictionary<int, T> RemoveItem<T>(IDictionary<int, T> dict, int key)
{
    return dict.Where(kv => kv.Key != key)
               .ToDictionary(kv => kv.Key > key ? kv.Key - 1 : kv.Key,
                             kv => kv.Value);
}

然后就这样称呼它:

var twoRemoved = RemoveItem(dict, 2);

请注意,这不会修改原始字典对象,而是创建一个新的字典对象,其中 key 之后的键向下移动 1 并删除了键值 key 的原始项。

这是一个确实修改原始字典并可能提供稍微更好的性能和内存使用的版本:

public static void RemoveItem2<T>(IDictionary<int, T> dict, int key)
{
    dict.Remove(key);
    T item;
    while (dict.TryGetValue(++key, out item))
    {
        dict.Remove(key);
        dict[key - 1] = item;               
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2021-10-25
    • 2020-04-18
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多