-1

我目前有一个字典,它在程序开始时加载了数据,它类似于:

  Dictionary<string, List<KeyValuePair<string,string>>> variants =
    new Dictionary<string, List<KeyValuePair<string, string>>>();

如果我想访问特定字符串的 Keyvaluepair 列表,我将如何引用它...

这是对它的理解:每个列表都有一个标识符(即字符串)->字符串导致Keyvaluepairs列表,我想随机选择它们

4

4 回答 4

3

让我们分解一下:

// 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();
于 2013-02-05T19:54:32.340 回答
1

您使用[]运算符。

将值放入哈希表中,

像这样:variants[key] = valueHere;

并从哈希表中获取值,

var valueHere = variants[key];

于 2013-02-05T19:45:49.290 回答
1

很难理解你到底在追求什么。这有帮助吗?

using System;
using System.Collections.Generic;

namespace SO14715593
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, List<KeyValuePair<string, string>>> variants = new Dictionary<string, List<KeyValuePair<string, string>>>();
            variants["test"] = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("key1", "item1"),
                    new KeyValuePair<string, string>("key2", "item2"),
                    new KeyValuePair<string, string>("key3", "item3")
                };

            Random random = new Random();
            int index = random.Next(variants["test"].Count);
            Console.WriteLine("{0};{1}", variants["test"][index].Key, variants["test"][index].Value);
        }
    }
}
于 2013-02-05T19:51:38.707 回答
0

你可以使用类似的东西:

var list = variants[stringToGetCorrespondingList]

于 2013-02-05T19:48:53.503 回答