ソースコード
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();
}
}