哈希集字典中的值的组合
作者:互联网
我有一个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?"
...
我想让这个尽可能抽象,以便可以在哈希集中添加尽可能多的键和值.
我尝试递归地执行此操作,但是我对此不太满意,我无法提出一个基本案例…我想您可以使用linq来执行此操作,但我对linq一点都不熟悉.
我使用Dictionary< string,HashSet< string>>的原因因为我正在收集信息,所以我想保留这种数据结构.
谢谢!
解决方法:
给定问题中提供的示例数据:
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);
}
标签:dictionary,combinatorics,linq,c,recursion 来源: https://codeday.me/bug/20191120/2044387.html