【发布时间】:2018-05-07 02:23:00
【问题描述】:
我已经搞砸了这几天了,我无法理解它:
我有以下结构:
Dictionary<string, HashSet<string>>
包含以下数据:
P1 S1, S2
P2 S1, S2
其中 P 前缀值是字典键,S 前缀值是 HashSet 值。
我需要的是下面的输出列表,
P1, P2, S1, S2
如果我有以下起始值:
P1 S1, S2
P2 S1
输出列表应该是:
P1, P2, S1, P1, S2
如果多个字典项的HashSet中有相似的值,应该将它们组合在一起,这就是为什么P1,P2有S1,P1只有S2
这里有一个小TestApp,可以澄清更多:
static void Main(string[] args)
{
var start = new Dictionary<string, HashSet<string>>();
var output = new List<string>();
//example1
start.Add("P1", new HashSet<string> { "S1", "S2" });
start.Add("P2", new HashSet<string> { "S1", "S2" });
output = HocusPocus(start);
PrintResult(output); // should be P1, P2, S1, S2
//example 2
start.Clear();
start.Add("P1", new HashSet<string> { "S1", "S2" });
start.Add("P2", new HashSet<string> { "S1" });
output = HocusPocus(start);
PrintResult(output); // should be P1, P2, S1, P1, S2
//example 3
start.Clear();
start.Add("P1", new HashSet<string> { "S1", "S2", "S3" });
start.Add("P2", new HashSet<string> { "S1" });
start.Add("P3", new HashSet<string> { "S1", "S2" });
output = HocusPocus(start);
PrintResult(output); // should be P1, P2, P3, S1, P1, P3, S2, P1, S3
Console.ReadKey();
}
public static List<string> HocusPocus(Dictionary<string, HashSet<string>> data)
{
// magic happens here
}
public static void PrintResult(List<string> result)
{
result.ForEach(x => Console.Write($"{x},"));
Console.WriteLine();
}
【问题讨论】:
-
你能更明确地说你真正想要发生的事情吗?我可以尝试从您的输出中猜测,但它不是很清楚。什么是 P 和 S?
-
当您创建一个字符串哈希集时,您通常会使用不属于普通数据的字符进行合并,例如“P1^P2^S1^P1^S2”。
-
你尝试过什么吗?我们为什么要做你的工作?构建一个循环来迭代您的字典并将值放入扁平列表中并不难。无论如何,输出应该是
P1, P2, S1, S2或P1, P2, S1, P1, S2。 -
当然,我已经尝试了一些东西,比如循环和其他东西,但这只能让我到目前为止。它是收集字典键、比较 HashSet 值、相交它们的组合......
标签: c# dictionary hashset