コガネブログ

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

【C#】Dictionary からランダムにキーや値を取得する拡張メソッド

ソースコード

using System;
using System.Collections.Generic;
using System.Linq;

public static class DictionaryExt
{
    private static Random m_random;

    private static Random random => m_random ?? ( m_random = new Random() );

    public static KeyValuePair<TKey, TValue> RandomAt<TKey, TValue>
    ( 
        this Dictionary<TKey, TValue> source 
    )
    {
        if ( source == null )
        {
            throw new ArgumentNullException( nameof( source ) );
        }

        return source.ElementAt( random.Next( 0, source.Count ) );
    }

    public static TKey RandomAt<TKey, TValue>
    ( 
        this Dictionary<TKey, TValue>.KeyCollection source 
    )
    {
        if ( source == null )
        {
            throw new ArgumentNullException( nameof( source ) );
        }

        return source.ElementAt( random.Next( 0, source.Count ) );
    }

    public static TValue RandomAt<TKey, TValue>
    ( 
        this Dictionary<TKey, TValue>.ValueCollection source 
    )
    {
        if ( source == null )
        {
            throw new ArgumentNullException( nameof( source ) );
        }

        return source.ElementAt( random.Next( 0, source.Count ) );
    }
}

使用例

using System.Collections.Generic;

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

        // キーと値のペアをランダムに取得
        var pair = table.RandomAt();

        // キーをランダムに取得
        var key = table.Keys.RandomAt();

        // 値をランダムに取得
        var value = table.Values.RandomAt();
    }
}