どうも、ちょげ(@chogetarou)です。
Dictionary(連想配列)からランダムにキーと値のペアを持つ要素を取得する方法を紹介します。
方法

Dictionary(連想配列)からランダムに要素を取得するには、System.LinqのElementAt()を使います。
まず、System.Linqを導入します。
using System.Linq;
次に、Randomクラスを生成します。
そして、DictionaryからElementAt()を呼び出します。
ElementAt()の引数でRandomクラスのインスタンスからNext()メソッドを呼び出します。
Next()メソッドの第1引数に「0」、第2引数にDictionaryのCountプロパティを指定します。
Random rnd = new Random();
KeyValuePair<TKey, TValue> = dict.ElementAt(rnd.Next(0, dict.Count));
上記のElementAt()は、Dictionary(連想配列)からランダムに要素を取得します。
使用例
using System;
using System.Linq;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
Dictionary<string, int> numbers = new Dictionary<string, int>()
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 },
};
Random rnd = new Random();
KeyValuePair<string, int> rndItem = numbers.ElementAt(rnd.Next(0, numbers.Count));
Console.WriteLine("{0} : {1}", rndItem.Key, rndItem.Value);
}
}
コメント