Wednesday, February 9, 2011

Programmatically iterating through discussion lists

On further testing, I've discovered that my last post wasnt quite accurate.

Each post in a discussion thread is actually a folder. Replies to that post are kept in that folder. So if you do a recursive CAML query by ID on the entire list, for some strange reason, you get back all the replies - for other posts as well.

So the better way of doing it is to iterate through the posts by iterating through the ListItemCollection on the discussion list - which gives you all the posts. To get all the replies, use the following simple code:

foreach (int topicID in topics)
{
SPQuery q = new SPQuery();

SPListItem item = list.GetItemById(topicID);
q.Folder = item.Folder;


SPListItemCollection replies = null;

replies = list.GetItems(q);

foreach (SPListItem reply in replies)
{
//There's usually no subject, just the body
Console.WriteLine(reply["Body"].ToString());


Console.WriteLine();
Console.WriteLine();
}
}

1 comment:

  1. Was struggling to find a way to iterate through the discussion list in a hierarchy. This post was really helpful.

    ReplyDelete