コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】Dictionary から指定したキーの要素を取得してから削除する拡張メソッド

ソースコード

using System.Collections.Generic;

public static class DictionaryExt
{
    public static bool Remove<TKey, TValue>
    (
        this Dictionary<TKey, TValue> self, TKey key,
        out  TValue                   value
    )
    {
        self.TryGetValue( key, out value );
        return self.Remove( key );
    }
}

使用方法

using System;
using System.Collections.Generic;

public static class Program
{
    private static void Main()
    {
        var table = new Dictionary<int, string>
        {
            { 1, "フシギダネ" },
            { 2, "フシギソウ" },
            { 3, "フシギバナ" },
        };

        table.Remove( 1, out var value );
        
        foreach ( var n in table )
        {
            Console.WriteLine( n );
        }
        
        Console.WriteLine( value );
    }
}

参考サイト様