让我们分解一下:
// 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();