Sorting visiblePosts in PostList.cs.aspx

Topics: ASP.NET 2.0, Controls
Mar 5, 2008 at 1:52 PM
I like to sort the post list by a custom field (Postlist.cs.aspx). Any ideas the best method to do it ?

Thanks,
Gavin



/// <summary>
/// Binds the list of posts to individual postview.ascx controls
/// from the current theme.
/// </summary>
private void BindPosts()
{
if (Posts == null || Posts.Count == 0)
{
hlPrev.Visible = false;
return;
}

List<Post> visiblePosts = Posts.FindAll(delegate(Post p) { return p.IsVisible; });
string customField = "weight";



// Sort the Post List by a custom field
// post.GetCustomFieldValue(customField);

Coordinator
Mar 6, 2008 at 11:03 PM
Sure. If you want to sort by the Title property for instance, you can write this:

visiblePosts.Sort(delegate(Post p1, Post p2) { return String.Compare(p1.Title, p2.Title); });
Mar 8, 2008 at 2:55 PM
Edited Mar 8, 2008 at 2:56 PM
Thank you, never really done delegates in .NET, in Xcode there really useful (but may not be the same thing). Must read up on them.

So heres what I did if anyone out there needs to do this...

To sort a CustomField which is a string

visiblePosts.Sort(delegate(Post p1, Post p2) {
return String.Compare((string)p1.GetCustomFieldValue(customField),
(string)p2.GetCustomFieldValue(customField)); });



To sort a custom field which is an integer.

string customField = "Weight";
visiblePosts.Sort(delegate(Post p1, Post p2)
{
int customField1 = 0;
String cf1 =(string)p1.GetCustomFieldValue(customField);
if (cf1 != "") customField1 = int.Parse(cf1);

int customField2 = 0;
String cf2 = (string)p2.GetCustomFieldValue(customField);
if (cf2 != "") customField2 = int.Parse(cf2);

return customField1 - customField2;
});
Mar 8, 2008 at 3:26 PM
I'm not 100% sure (i.e. I haven't tested it), but I think the integer sorting would be much better done by

visiblePosts.Sort( (p1, p2) =>
{
int i1, i2 = int.MinValue;
int.TryParse(p1.GetCustomFieldValue(customField), out i1);
int.TryParse(p2.GetCustomFieldValue(customField), out i2);
return int.Compare(i1, i2);
});
Mar 9, 2008 at 3:11 PM
Thanks Domenic, Don't seem to have a Compare method.

This what seemed to work for me

visiblePosts.Sort(delegate(Post p1, Post p2)
{
int i1, i2 = int.MinValue;
int.TryParse((string)p1.GetCustomFieldValue(customField),out i1);
int.TryParse((string)p2.GetCustomFieldValue(customField),out i2);
return i1 - i2;
});