Utility method to get SharePoint 2010 blog posts and their comments
Say no more. Here it is. Self-explanatory.
public class Post
{
public string Title;
public string Body;
public DateTime Published;
public IEnumerable<Comment> Comments;
}
public class Comment
{
public string Title;
public string Body;
public string Author;
public DateTime Created;
}
static IEnumerable<Post> GetBlogPosts()
{
// TODO: get blog's site collection's url
using (SPSite s = new SPSite("https://server/sites/myblog"))
{
SPWeb w = s.RootWeb;
// get posts
List<Post> posts = new List<Post>();
SPList pl = w.Lists["posts"];
SPQuery pq = new SPQuery() { ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Body' /><FieldRef Name='PublishedDate' />" };
foreach (SPListItem pli in pl.GetItems(pq))
{
// get post
posts.Add(new Post() { Body = (string)pli["Body"], Title = (string)pli["Title"], Published = (DateTime)pli["PublishedDate"], Comments = new List<Comment>() });
}
// get comments
SPList cl = w.Lists["comments"];
SPQuery cq = new SPQuery() { ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Body' /><FieldRef Name='Author' /><FieldRef Name='Created' /><FieldRef Name='PostTitle' />" };
foreach (SPListItem cli in cl.GetItems(cq))
{
SPFieldLookupValue plookup = new SPFieldLookupValue((string)cli["PostTitle"]);
(from Post p in posts where p.Title == plookup.LookupValue select p).FirstOrDefault<Post>().Comments.Add(new Comment() { Body = (string)cli["Body"], Title = (string)cli["Title"], Author = (string)cli["Author"], Created = (DateTime)cli["Created"] });
}
// return
return (posts);
}
}