どうも、ちょげ(@chogetarou)です。
Dictionary(連想配列)からランダムにKey(キー)を取得する方法を紹介します。
方法

Dictionary(連想配列)からランダムにKey(キー)を取得するには、System.LinqのElementAt()を使います。
まず、System.Linqを導入します。
using System.Linq;
次に、Randomクラスを生成します。
そして、DictionaryからElementAt()を呼び出します。
ElementAt()の引数でRandomクラスのインスタンスからNext()メソッドを呼び出します。
Next()メソッドの第1引数に「0」、第2引数にDictionaryのCountプロパティを指定します。
あとは、ElementAt()のKeyにアクセスします。
Random rnd = new Random();
var rndKey = dict.ElementAt(rnd.Next(0, dict.Count)).Key;
上記のElementAt().Keyは、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();
string rndKey = numbers.ElementAt(rnd.Next(0, numbers.Count)).Key;
Console.WriteLine(rndKey);
}
}
コメント