「C#」Dictionaryのすべての要素を削除する

2021年10月8日

書式
var 変数名 = new Dictionary<int, string>();
変数名.Clear();

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
using System.Collections.Generic;
class Arkgame
{
public static void Main()
{
//Dictionaryのインスタンスの宣言
var cft = new Dictionary<int, string>();
//Addメソッドで(key,value)を追加
cft.Add(100, "東京");
cft.Add(200, "大阪");
cft.Add(300, "福岡");
Console.WriteLine("Dictionaryの要素を削除する前結果");
// foreach文で辞書のキー、値を出力
foreach (var ct in cft)
{
Console.WriteLine("キー: " + ct.Key + " 値: " + ct.Value);
}
//すべての要素を削除
cft.Clear() ;
Console.WriteLine("Dictionaryの要素を削除する後結果");
Console.WriteLine("要素数: " + cft.Count);
Console.ReadKey();
}
}
using System; using System.Collections.Generic; class Arkgame { public static void Main() { //Dictionaryのインスタンスの宣言 var cft = new Dictionary<int, string>(); //Addメソッドで(key,value)を追加 cft.Add(100, "東京"); cft.Add(200, "大阪"); cft.Add(300, "福岡"); Console.WriteLine("Dictionaryの要素を削除する前結果"); // foreach文で辞書のキー、値を出力 foreach (var ct in cft) { Console.WriteLine("キー: " + ct.Key + " 値: " + ct.Value); } //すべての要素を削除 cft.Clear() ; Console.WriteLine("Dictionaryの要素を削除する後結果"); Console.WriteLine("要素数: " + cft.Count); Console.ReadKey(); } }
using System;
using System.Collections.Generic;
class Arkgame
{
    public static void Main()
    {
        //Dictionaryのインスタンスの宣言
        var cft = new Dictionary<int, string>();

        //Addメソッドで(key,value)を追加
        cft.Add(100, "東京");
        cft.Add(200, "大阪");
        cft.Add(300, "福岡");

        Console.WriteLine("Dictionaryの要素を削除する前結果");
        // foreach文で辞書のキー、値を出力
        foreach (var ct in cft)
        {
            Console.WriteLine("キー: " + ct.Key + " 値: " + ct.Value);
        }
        
        //すべての要素を削除
        cft.Clear() ;
        
        Console.WriteLine("Dictionaryの要素を削除する後結果");
        Console.WriteLine("要素数: " + cft.Count); 


        Console.ReadKey();
    }
}

実行結果
Dictionaryの要素を削除する前結果
キー: 100 値: 東京
キー: 200 値: 大阪
キー: 300 値: 福岡
Dictionaryの要素を削除する後結果
要素数: 0

C#

Posted by arkgame