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

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