[C#]Dictionary(辞書)のキーの値を更新するには?

C#

どうも、ちょげ(@chogetarou)です。

Dictionaryの特定のキーの値を更新する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

Dictionaryの特定のキーの値を更新するには、=を使います。

まず、「辞書名[キー]」のように、辞書名の後に[キー]を記述します。

そして、辞書名[キー]に新しい値を代入します。

myDict[key] = newValue;

上記の=で、[]内に指定したキーの値が、代入した値に更新されます。

使用例

using System;
using System.Collections.Generic;
public class Example
{
    public static void Main()
    {
        Dictionary<string, int> numbers = new Dictionary<string, int>()
	    {
	        { "one", 1 },
	        { "two", 2 },
	        { "three", 0 },
	        { "four", 4 },
	        { "five", 0 },
	    };
	    
	    numbers["three"] = 3;
	    numbers["five"] = 5;
	    
	    foreach(var item in numbers)
	    {
	        Console.WriteLine(item.Key + ":" + item.Value);
	    }
    }
}
/*
    出力:
    one:1
    two:2
    three:3
    four:4
    five:5
*/

コメント

タイトルとURLをコピーしました