转换结构的算法(传递闭包?)

时间:2011-09-15 08:39:26

标签: c# dictionary closures tuples

我的源结构是字典,如下所示:

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

我真的需要一些帮助来实现这一点,我在传递闭包的方式上有一些提示,但我真的可以;我的头围绕它。任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:3)

从字典方法来看,我假设它被声明为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();

请确保您没有任何周期:)