どうも、ちょげ(@chogetarou)です。
Dictionary(辞書)のキー(Key)を変更する方法を紹介します。
方法

Dictionary(辞書)のキー(Key)を変更するには、Remove()を使います。
まず、Dictionary(辞書)の新しいキーに古いキーの値を代入します。
Dictionary(辞書)からRemove()を呼び出します。
そして、Remove()の引数に古いキーを指定します。
//newKey=新しいキー、oldKey=古いキー
dict[newKey] = dict[oldKey];
dict.Remove(oldKey);
上記の処理で、Dictionary(辞書)のキーを変更できます。
使用例
using System;
using System.Collections.Generic;
public class Sample
{
public static void Main()
{
Dictionary<string, int> numbers = new Dictionary<string, int>()
{
{ "one", 1 },
{ "two", 2 },
{ "さん", 3 },
{ "four", 4 },
{ "five", 5 },
};
//キーの更新
numbers["three"] = numbers["さん"];
numbers.Remove("さん");
foreach (var item in numbers)
{
Console.WriteLine(item.Key + "=" + item.Value);
}
}
}
出力:
one=1
two=2
four=4
five=5
three=3
コメント