开发者

Algorithm to transform a structure (transitive closure?)

My source structure is either a Dictionary looking like:

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

Or a list of tuples looking like:

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("Social开发者_如何学JAVAMedia", "Facebook");
list.Add(Tuple.Create("Medium", "SocialMedia");

These are associations between items, maybe best described as an inheritance tree. Medium being the most general class, A the most specialized.

What I'm looking for is a way to rearrange the items to look like the following:

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

I really need some help accomplishing this, I've had some tips in the way of a transitive closure, but I really can;t wrap my head around it. Any help would be really much appreciated.


From the dictionary approach, which I assume was meant to be declared as a 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;
            }
        }
    }
}

Then:

var query = from name in dictionary.Keys
            from value in TransitiveValues(name, dictionary)
            select Tuple.Create(name, value);
var list = query.ToList();

Just make sure you don't have any cycles :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜