从键值列表中获取组合

时间:2012-09-18 20:15:44

标签: c# combinations

我在dict中有dict<string, list<string>>,个3个键,第一个键有2个值,secodn 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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分: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...
            }
        }

答案 3 :(得分: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];
    }
}

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

答案 4 :(得分:0)

快速&amp;脏,但你可以抛光这种方法。结果列表包含预期结果:

用法:

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);
    }
}