score:23

Accepted answer
   public class comment
    {
        public int id { get; set; }
        public int parentid { get; set; }
        public string text { get; set; }        
        public list<comment> children { get; set; }
    }

    class program
    {
        static void main()
        {
        list<comment> categories = new list<comment>()
            {
                new comment () { id = 1, text = "item 1", parentid = 0},
                new comment() { id = 2, text = "item 2", parentid = 0 },
                new comment() { id = 3, text = "item 3", parentid = 0 },
                new comment() { id = 4, text = "item 1.1", parentid = 1 },
                new comment() { id = 5, text = "item 3.1", parentid = 3 },
                new comment() { id = 6, text = "item 1.1.1", parentid = 4 },
                new comment() { id = 7, text = "item 2.1", parentid = 2 }
            };

            list<comment> hierarchy = new list<comment>();
            hierarchy = categories
                            .where(c => c.parentid == 0)
                            .select(c => new comment() { 
                                  id = c.id, 
                                  text = c.text, 
                                  parentid = c.parentid, 
                                  children = getchildren(categories, c.id) })
                            .tolist();

            hieararchywalk(hierarchy);

            console.readline();
        }

        public static list<comment> getchildren(list<comment> comments, int parentid)
        {
            return comments
                    .where(c => c.parentid == parentid)
                    .select(c => new comment { 
                        id = c.id, 
                        text = c.text, 
                        parentid = c.parentid, 
                        children = getchildren(comments, c.id) })
                    .tolist();
        }

        public static void hieararchywalk(list<comment> hierarchy)
        {
            if (hierarchy != null)
            {
                foreach (var item in hierarchy)
                {
                    console.writeline(string.format("{0} {1}", item.id, item.text));
                    hieararchywalk(item.children);
                }
            }
        }

score:5

your comment class can be seen as a graph and your problem is a graph traversal problem.

you can't really define recursive problems through linq, but the problem can very easily be resolved by a simple recursive method.

score:12

ienumerable<comment> getchild(int id)
{
    return table.where(x => x.parentid == id || x.id== id)
                .union(table.where(x => x.parentid == id)
                            .selectmany(y => getchild(y.id))
    );
}

Related Query