それを分解しましょう:
// This is your dictionary.
Dictionary<string, List<KeyValuePair<string,string>>> variants = new Dictionary<string, List<KeyValuePair<string, string>>>();
// Let's get the list of variants for a given key.
string key = "myKey";
List<KeyValuePair<string,string>> variantsForKey = variants[key];
// If we wanted to get the first variant, we'd use one of these:
KeyValuePair<string,string> firstVariant = variantsForKey[0];
firstVariant = variantsForKey.First(); // Using Linq for fun and profit!
// Now, we want a random variant? No problem!
Random rand = new Random(); // Remember to initialize this only once!
int listLength = variantsForKey.Count;
int randomVariantIndex = rand.Next(0, listLength );
KeyValuePair<string,string> randomVariant = variantsForKey[randomVariantIndex];
出来上がり!
ここで、実行したいのは、これらの最後の3行を拡張メソッドでラップすることです。
public static class VariantExtensions
{
private static Random rand = new Random();
public static KeyValuePair<string,string> GetRandomVariant(this List<KeyValuePair<string,string>> variantsForKey)
{
int listLength = variantsForKey.Count;
int randomVariantIndex = rand.Next(0, listLength );
return variantsForKey[randomVariantIndex];
}
}
そして今、あなたはこれを使うことができます:
Dictionary<string, List<KeyValuePair<string,string>>> variants = ...;
string key = "myKey";
KeyValuePair<string,string> randomVariant = variants[key].GetRandomVariant();