在哈希集的字典中查找值的组合

时间:2015-04-13 15:01:12

标签: c# linq dictionary recursion combinatorics

我有一个Dictionary<string, HashSet<string>>我希望通过HashSet找到所有组合,而不需要重复。例如(虚拟数据):

Keys          Values (HashSet)

"greeting"     "Hello" "Hi" "Hey" "Howdy" ...
"Name"         "Tom" "Angel" "Edward" ...
"question"     "how are you?" "can you help me?" "is everything okay?" ...
    ...                  ...
    ...                ....

我希望输出为某种集合,每个值为:

"Hello Tom how are you?"
"Hello Tom can you help me?"
"Hello Tom is everything okay?"
"Hello Angel how are you?"
"Hello Angel can you help me?"
"Hello Angel is everything okay?"
"Hello Edward how are you?"
...

"Hi Tom how are you?"
"Hi Tom can you help me?"
"Hi Tom is everything okay?"
"Hi Angel how are you?"
...

我希望尽可能抽象这个我可以在hashset中添加尽可能多的键和值的地方。

我试图以递归的方式做到这一点,但我对此并不太强大,我无法想出一个基本案例...我认为你可以用linq做到这一点,但我根本不熟悉linq。

我使用Dictionary<string, HashSet<string>>的原因是因为我收集信息的方式,所以我想保留这个数据结构。

谢谢!

2 个答案:

答案 0 :(得分:3)

鉴于问题中提供的示例数据:

var data = new Dictionary<string, HashSet<string>>
{
    {"greeting", new HashSet<string> {"Hello", "Hi", "Hey", "Howdy"}},
    {"Name", new HashSet<string> {"Tom", "Angel", "Edward"}},
    {"question", new HashSet<string> {"how are you?", "can you help me?", "is everything okay?"}}
};

没有任意键,这里有一个简单的方法来使用LINQ:

var collection = from g in data["greeting"]
    from n in data["Name"]
    from q in data["question"]
    select string.Format("{0} {1} {2}", g, n, q);

使用this answer中的CartesianProduct扩展名方法如下所示:

var collection = data.Select(x => x.Value).CartesianProduct().Select(x => x.Aggregate((a, b) => a + " " + b));

在任何一种情况下,这里都是我用来在控​​制台应用中显示输出的foreach

foreach (var line in collection)
{
    Console.WriteLine(line);
}

答案 1 :(得分:0)

一个简单的解决方案就是......

Dictionary<string, HashSet<string>> test = new Dictionary<string, HashSet<string>>();
        test.Keys.ToList().ForEach(key =>
        {
            test[key].ToList().ForEach(value => Console.WriteLine("key key:" + "value:" + value));
        });
相关问题