我的源代码结构是一个Dictionary,如下所示:
new Dictionary<string, string>();
dic.Add("Dinges", new List<String>() { "A", "B" });
dic.Add("Facebook", new List<String>() { "Dinges" });
dic.Add("SocialMedia", new List<String>() { "FaceBook" });
dic.Add("Medium", new List<String>() { "SocialMedia" })
或如下所示的元组列表:
new List<Tuple<String, String>>();
list.Add(Tuple.Create("Dinges", "A");
list.Add(Tuple.Create("Dinges", "B");
list.Add(Tuple.Create("Facebook", "Dinges");
list.Add(Tuple.Create("SocialMedia", "Facebook");
list.Add(Tuple.Create("Medium", "SocialMedia");
这些是项目之间的关联,最好将其描述为继承树。中级是最普通的班级,A是最专业的班级。
我正在寻找的是一种重新排列项目的方式,如下所示:
new List<Tuple<String, String>>();
list.Add(Tuple.Create("Dinges", "A");
list.Add(Tuple.Create("Dinges", "B");
list.Add(Tuple.Create("Facebook", "Dinges");
list.Add(Tuple.Create("Facebook", "A");
list.Add(Tuple.Create("Facebook", "B");
list.Add(Tuple.Create("SocialMedia", "A");
list.Add(Tuple.Create("SocialMedia", "B");
list.Add(Tuple.Create("SocialMedia", "Dinges");
list.Add(Tuple.Create("SocialMedia", "Facebook");
list.Add(Tuple.Create("Medium", "A");
list.Add(Tuple.Create("Medium", "B");
list.Add(Tuple.Create("Medium", "Dinges");
list.Add(Tuple.Create("Medium", "FaceBook");
list.Add(Tuple.Create("Medium", "SocialMedia");
我确实需要一些帮助来完成此任务,在传递闭包的方式上有一些技巧,但是我实在无法解决。任何帮助将不胜感激。
最佳答案
从字典方法中,我认为该方法应声明为Dictionary<string, List<string>>
:
private static IEnumerable<string> TransitiveValues(string name,
Dictionary<string, List<string>> lookup)
{
yield return name;
List<string> children;
if (lookup.TryGetValue(name, out children))
{
foreach (string child in children)
{
foreach (string value in TransitiveValues(child, lookup))
{
yield return value;
}
}
}
}
然后:
var query = from name in dictionary.Keys
from value in TransitiveValues(name, dictionary)
select Tuple.Create(name, value);
var list = query.ToList();
只要确保您没有任何循环即可:)
关于c# - 转换结构的算法(传递闭包?),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7428076/