从字典中删除项目后,如何相应地更改其他键

本文关键字:其他 何相应 字典 删除项目 | 更新日期: 2023-09-27 18:21:12

例如,字典包含

key:   1 2 3 4 5
value: a b c d e

一旦你删除了b项,字典就会像这样,

key:   1 3 4 5 
value: a c d e

然而,我希望密钥是这样的,

key:   1 2 3 4
value: a c d e

有什么可能的方法可以做到这一点吗?

从字典中删除项目后,如何相应地更改其他键

您想要的是ArrayList,而不是字典。

如果您想将其保留为词典,可以将其转换为列表,然后删除条目,然后将其重新转换为词典。

var list = new List<string>();
foreach(var item in dictionary)
{
    list.Add(item.Value);
}
var newDict = new Dictionary<int, string>();
for(int i = 1; i < list.Count + 1; i++)
{
    newDict.Add(i,list[i]);
}

不过不要这样做。

正如其他人所说,这不是正确的方法。然而,这是可能的。这是另一种方式:

public static void Test()
{
    var foo = new Dictionary<int, string> { { 1, "a" }, { 2, "b" }, { 3, "c" }, { 4, "d" }, { 5, "e" } };
    RemoveItemByKey(ref foo, 3);
    RemoveItemByValue(ref foo, "a");
    foreach (var kvp in foo)
    {
        Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);
    }
    // Output:
    // 1: b
    // 2: d
    // 3: e
}
public static void RemoveItemByValue(ref Dictionary<int, string> dictionary, string valueToRemove)
{
    foreach (var kvp in dictionary.Where(item=>item.Value.Equals(valueToRemove)).ToList())
    {
        RemoveItemByKey(ref dictionary, kvp.Key);
    }
}
public static void RemoveItemByKey(ref Dictionary<int, string> dictionary, int keyToRemove)
{           
    if (dictionary.ContainsKey(keyToRemove))
    {
        dictionary.Remove(keyToRemove);
        int startIndex = 1;
        dictionary = dictionary.ToDictionary(keyValuePair => startIndex++, keyValuePair => keyValuePair.Value);
    }
}