Search code examples
c#listnested-setsthreaded-comments

How to build a threaded Comment System in C#? Help


Im building a Threaded Comment System for a website of mine and I ran into a problem...

I have a list PULLED FROM A DATABASE that has a ID field and a Parent ID Field. The parent ID field can be null, but the ID field will NEVER be null.

Since this will be a threaded comment system, I organize the list to where the ID is the top one, but if a parent ID exists, then it would be inserted under the ID. Then this can go on for infinity also. So the second level now also has an ID and and I want to insert any item with a parent ID of that ID under it.

For example:

---1. Blah

--------2. Blah Blah -> ParentID=1

-----------3. Blah Blah -> parentID=2

-------------- 4. Blah Blah ->parentID=3

----------- 3.Blah Blah -> parentID=2

--------2. Blah Blah -> parentID=1

I think you get the point.

So here is what I have so far...

List<comment> finalList = new List<comment>();
    for (int i = 0; i < getComments.Count(); i++)
    {
        string item = getComments[i].parentComment;
        getComments[i].threadID = 1;
        finalList.Add(getComments[i]);
        for (int ii = 0; ii < getComments.Count(); ii++)
        {
            if (getComments[ii].commentID == item)
            {
                getComments[ii].threadID = 2;
                finalList.Add(getComments[i]);
            }
        }
    }

It seems to sort it half way, but not truly... The ThreadID is of course how far it gets planted to the right.


Solution

  • Thanks all for your help guys. I do appreciate it.

    I did though, find something by a guy that wrote absolutely everything for it.

    http://www.scip.be/index.php?Page=ArticlesNET23

    http://www.scip.be/index.php?Page=ArticlesNET09

    http://www.scip.be/index.php?Page=ArticlesNET18