Sorting on seperate pages

Jan 27, 2011 at 9:12 PM

Our client would like three links at the top of their blog, "most recent" (which would sort the blog postings by date, which is the default right now), the next is "most comments", I would like to create a seperate page that would rank the blog postings by most comments. If someone goes to default.aspx I would like it to be sorted by date, on this new page (mostcomments.aspx) I would like it to be sorted by most comments.

Is this possible? I thought I had a solution for it, but once its sorted by most comments, it remained sorted like that on all pages, including the main page (default.aspx).

Coordinator
Jan 28, 2011 at 9:54 AM

If you sort Post.Posts, that will sort the main list of posts that is used throughout the blog.  I'm guessing that's what you are doing.

Instead, you will want to create a new list of posts that you can sort.  When you do this, that new list is being sorted independently of Post.Posts -- even though the posts it contains in the list are the same exact posts that Post.Posts contains (the posts are not duplicated).  Here's a code sample of creating a new list (this is the key part), the list contains the same posts that are in Post.Posts, and then it sorts the new list ... rather than sorting Post.Posts.  This sample is also sorting so the posts with the most comments come first.

// put the posts into a new list that can be sorted and
// the sorting doesn't affect the main Post.Posts list.
List<Post> posts = new List<Post>(Post.Posts);
posts.Sort((p1, p2) => p2.ApprovedComments.Count.CompareTo(p1.ApprovedComments.Count));
Jan 28, 2011 at 7:45 PM

Thanks Ben. Where would I put this code?

Coordinator
Jan 30, 2011 at 9:52 AM

The code can go anywhere you want to feed the list of "most commented" posts to (a page, a widget, etc).

Here's a standalone page that uses this code.  If you create a new file named "posts-with-most-comments.aspx" (or similar), and put the following content into it.  It'll display the posts, ordered so the ones with the most comments come first.

<%@ Page Language="C#" AutoEventWireup="true" Inherits="BlogEngine.Core.Web.Controls.BlogBasePage" %>
<%@ Register Src="User controls/PostList.ascx" TagName="PostList" TagPrefix="uc1" %>
<%@ Import Namespace="BlogEngine.Core" %>

<script runat="server">

	protected override void OnLoad(EventArgs e)
	{
		base.OnLoad(e);
		
		// put the posts into a new list that can be sorted and
		// the sorting doesn't affect the main Post.Posts list.
		List<Post> posts = new List<Post>(Post.Posts);
		posts.Sort((p1, p2) => p2.ApprovedComments.Count.CompareTo(p1.ApprovedComments.Count));
		
		PostList1.Posts = posts.ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
	}

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" Runat="Server">
	<div id="most-comments-posts">
		<uc1:PostList ID="PostList1" runat="server" />
	</div>
</asp:Content>