0

dict<string, list<string>>,在 dict 中有 3 个键,第一个键有 2 个值,第二个键有 3 个值,第三个键有 3 个值。如果我从每个值集中获得一个值,那么我将拥有 2*3*3 = 18 个集合的组合 如何在 c# 中编码?

谢谢

编辑对不起没有说清楚

我想要这样的东西说我有这样的字典

 {"1",new List<String>(){"a", "b"}}, 
    {"2",new List<String>(){"c", "d", "e"}}, 
 {"3", new List<string>() {"f", "g"}

我想要这样的输出 acf,acg,adf,adg,aef,aeg bcf,bcg,bdf,bdg,bef,beg

4

5 回答 5

1

使用 Linq:

var dict = new Dictionary<String, List<String>>() { 
    {"1",new List<String>(){"a", "b"}},
    {"2",new List<String>(){"c", "d", "e"}},
    {"3",new List<String>(){"f", "g", "h"}},
};
var combis = from kv in dict
             from val1 in kv.Value
             from val2 in kv.Value
             select string.Format("{0}{1}", val1, val2);
foreach (var combi in combis)
    Console.WriteLine(combi);

演示:http: //ideone.com/nm7mY

于 2012-09-18T20:32:50.807 回答
0

我想你是这个意思?

Dictionary<string, int> dict = new Dictionary<string, int>
{
    { "Hello World", 1 },
    { "HelloWorld", 1 },
    { "Hello  World", 1 },
};

foreach (var item in dict) // var is of type KeyValuePair<string, int>
    Console.WriteLine(item.Key + ", " + item.Value);
于 2012-09-18T20:28:29.523 回答
0
        Dictionary<string, List<int>> storage = new Dictionary<string, List<int>>();
        storage.Add("key1", new List<int>() { 2, 7 });
        storage.Add("key2", new List<int>() { 8, 4, 1});
        storage.Add("key3", new List<int>() { 3, 9, 3 });
        foreach (string key in storage.Keys)
        {
            //access to single storage...
            List<int> subStorage = (List<int>)storage[key];
            foreach (int item in subStorage)
            {
                //access to single value inside storage...
            }
        }
于 2012-09-18T20:31:04.260 回答
0

如果我试图读取或编辑列表中的值,我会尝试以下操作:

Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
var arrayOfValues = dict.Values.ToArray();

for (int i = 0; i < arrayOfValues.Length; i++)
{
    for (int j = 0; j < arrayOfValues[i].Count; j++)
    {
        //read/edit arrayOfValues[i][j];
    }
}

您不需要递归,因为您知道“树”的部门。

于 2012-09-18T20:45:43.937 回答
0

又快又脏,但你可以擦亮这个方法。结果列表包含预期结果:

用法:

var dict = new Dictionary<String, List<String>>() { 
    {"1",new List<String>(){"a", "b"}},
    {"2",new List<String>(){"c", "d", "e"}},
    {"3",new List<String>(){"f", "g"}},
};

var collections = dict.Select(kvp => kvp.Value).ToArray();            
var result = new List<string>(); 
GetNextProduct(collections, 0, String.Empty, result);

产生结果的方法:

private static void GetNextProduct(IEnumerable<string>[] collections, int collectionIndex, string currentProduct, IList<string> results)
{
    var currentList = collections[collectionIndex];
    bool isLast = collections.Length == collectionIndex + 1;
    foreach (var s in currentList)
    {
        if (isLast) results.Add(currentProduct + s);
        else GetNextProduct(collections, collectionIndex + 1, currentProduct + s, results);
    }
}
于 2012-09-18T21:08:14.247 回答