Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7694759
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T21:23:32+00:00 2026-05-31T21:23:32+00:00

I have an adjacency list like this: A – A1 A – A2 A

  • 0

I have an adjacency list like this:

A   -  A1
A   -  A2
A   -  A3
A3  - A31
A31 - A311
A31 - A312

I am trying to obtain the following output:

{
    "name": "A",
    "children": [{
        "name": "A1"
    }, {
        "name": "A2"
    }, {
        "name": "A3",
        "children": [{
            "name": "A31",
            "children": [{
                "name": "A311"
            }, {
                "name": "A312"
            }]
        }]
    }]
};

I have a modestly large graph containing 100K links. What is a good way of doing this? I am thinking there is a very elegant recursive way of doing this but am not sure about how to create the JSON string directly.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T21:23:33+00:00Added an answer on May 31, 2026 at 9:23 pm

    Something like should work:

    static void Main(string[] args)
    {
        var adjList = new List<Link>
        {
            new Link("A","A1"),
            new Link("A","A2"),
            new Link("A","A3"),
            new Link("A3","A31"),
            new Link("A31","A311"),
            new Link("A31","A312"),
        };
    
        var rootsAndChildren = adjList.GroupBy(x => x.From)
               .ToDictionary(x => x.Key, x => x.Select(y => y.To).ToList());
        var roots = rootsAndChildren.Keys
               .Except(rootsAndChildren.SelectMany(x => x.Value));
    
        using (var wr = new StreamWriter("C:\\myjson.json"))
        {
            wr.WriteLine("{");
            foreach (var root in roots)
                AppendSubNodes(wr, root, rootsAndChildren, 1);
            wr.WriteLine("};");
        }
    }
    
    static void AppendSubNodes(TextWriter wr, string root, 
              Dictionary<string, List<string>> rootsAndChildren, int level)
    {
        string indent = string.Concat(Enumerable.Repeat(" ", level * 4));
        wr.Write(indent + "\"name\" : \"" + root + "\"");
        List<string> children;
        if (rootsAndChildren.TryGetValue(root, out children))
        {
            wr.WriteLine(",");
            wr.WriteLine(indent + "\"children\" : [{");
            for (int i = 0; i < children.Count; i++)
            {
                if (i > 0)
                    wr.WriteLine(indent + "}, {");
                AppendSubNodes(wr, children[i], rootsAndChildren, level + 1);
            }
            wr.WriteLine(indent + "}]");
        }
        else
        {
            wr.WriteLine();
        }
    }
    

    With Link being the following class:

    class Link
    {
        public string From { get; private set; }
        public string To { get; private set; }
        public Link(string from, string to)
        {
            this.From = from;
            this.To = to;
        }
    }
    

    Result of the previous code:

    {
        "name" : "A",
        "children" : [{
            "name" : "A1"
        }, {
            "name" : "A2"
        }, {
            "name" : "A3",
            "children" : [{
                "name" : "A31",
                "children" : [{
                    "name" : "A311"
                }, {
                    "name" : "A312"
                }]
            }]
        }]
    };
    

    EDIT :

    If you want to check the existence of graph cycles you can do the following (just after the creation of rootsAndChildren dictionary)

    var allNodes = rootsAndChildren.Keys.Concat(rootsAndChildren.SelectMany(x => x.Value)).Distinct();
    Func<string, IEnumerable<string>> getSuccessors =
        (x) => rootsAndChildren.ContainsKey(x) ? rootsAndChildren[x] : Enumerable.Empty<string>();
    
    var hasCycles = new Tarjan<string>().HasCycle(allNodes, getSuccessors);
    

    With Tarjan being the following class:

    // Please note that Tarjan does not detect a cycle due to a node 
    // pointing to itself. It's pretty trivial to account for that though...
    public class Tarjan<T>
    {
        private class Node
        {
            public T Value { get; private set; }
            public int Index { get; set; }
            public int LowLink { get; set; }
            public Node(T value)
            {
                this.Value = value;
                this.Index = -1;
                this.LowLink = -1;
            }
        }
        private Func<T, IEnumerable<T>> getSuccessors;
        private Dictionary<T, Node> nodeMaps;
        private int index = 0;
        private Stack<Node> stack;
        private List<List<Node>> SCC;
        public bool HasCycle(IEnumerable<T> nodes, Func<T, IEnumerable<T>> getSuccessors)
        {
            return ExecuteTarjan(nodes, getSuccessors).Any(x => x.Count > 1);
        }
        private List<List<Node>> ExecuteTarjan(IEnumerable<T> nodes, Func<T, IEnumerable<T>> getSuccessors)
        {
            this.nodeMaps = nodes.ToDictionary(x => x, x => new Node(x));
            this.getSuccessors = getSuccessors;
            SCC = new List<List<Node>>();
            stack = new Stack<Node>();
            index = 0;
            foreach (var node in this.nodeMaps.Values)
            {
                if (node.Index == -1)
                    TarjanImpl(node);
            }
            return SCC;
        }
        private IEnumerable<Node> GetSuccessors(Node v)
        {
            return this.getSuccessors(v.Value).Select(x => this.nodeMaps[x]);
        }
        private List<List<Node>> TarjanImpl(Node v)
        {
            v.Index = index;
            v.LowLink = index;
            index++;
            stack.Push(v);
            foreach (var n in GetSuccessors(v))
            {
                if (n.Index == -1)
                {
                    TarjanImpl(n);
                    v.LowLink = Math.Min(v.LowLink, n.LowLink);
                }
                else if (stack.Contains(n))
                {
                    v.LowLink = Math.Min(v.LowLink, n.Index);
                }
            }
            if (v.LowLink == v.Index)
            {
                Node n;
                List<Node> component = new List<Node>();
                do
                {
                    n = stack.Pop();
                    component.Add(n);
                } while (n != v);
                SCC.Add(component);
            }
            return SCC;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say I have a list that looks like this: <ul> <li id=q></li> <li
I have a list of (label, count) tuples like this: [('grape', 100), ('grape', 3),
I have an adjacency list of objects (rows loaded from SQL database with the
So far I have encountered adjacency list, nested sets and nested intervals as models
In mysql, I have a tree that is represented using the adjacency list model.
UPDATE Some answers so far have suggested using an adjacency list. How would an
So, I have a table like such: id|root|kw1|kw2|kw3|kw4|kw5|name 1| A| B| C| D| E|
I have a chained list like [root, foo, bar, blah] And I'd like to
I have an adjacency list in a database with ID and ParentID to represent
I have a class like this: template<class T> class AdjacencyList { public: void delete_node(const

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.