Login

How do I sort pages by multiple properties?

Versions: n/a, FAQ number: 70, Old FAQ number: 936

Q: How do I sort pages by multiple properties?

A: Create a filter that sorts the pages using a class that inherits the IComparer interface.

Below is a sample that sorts all pages in a PageList by PageChangedBy and PageChanged properties. The technique used is an implementation of the System.Collections.IComparer interface, check out the SortPagesComparer class to see how this is done. For more information about the IComparer interface see the .Net documentation.

using System;
using EPiServer;
using EPiServer.Core;
using EPiServer.Filters;
using EPiServer.WebControls;

protected EPiServer.WebControls.PageList pageList;

/// <summary>
/// This comparer sorts pages by PageChangedBy, Changed, 
/// both in ascending order.

/// </summary>
private sealed class SortPagesComparer : IComparer
{
  /// <summary>
  /// Compare two PageData objects.
  /// </summary>
  /// <param name="firstObject">First page to compare</param>
  /// <param name="secondObject">Second page to compare</param>
  /// <returns>
  /// -1 if first page is sorted before second,
  /// 1 if second page is sorted before first,
  /// 0 if both pages should be treated as equal
  /// </returns>

  public int Compare(object firstObject, object secondObject)
  {
    PageData firstPage = (PageData) firstObject;
    PageData secondPage = (PageData) secondObject;

    if (firstPage["PageChangedBy"].Equals(secondPage["PageChangedBy"]))
    {
      return firstPage.Changed.CompareTo(secondPage.Changed);
    }
    else
      return firstPage["PageChangedBy"].ToString().CompareTo(
                  secondPage["PageChangedBy"].ToString());
  }
}

private void SortPagesFilter(object sender, FilterEventArgs e)
{
  PageDataCollection pages = e.Pages;
  pages.Sort(new SortPagesComparer());
}

private void Page_Load(object sender, System.EventArgs e)
{
  pageList.Filter  += new FilterEventHandler(SortPagesFilter);

  DataBind();
}


Just a note about the CompareTo-function

As you probably know, when you say a.CompareTo(b) the function returns -1 if a is less than b, 0 if a equals b and 1 a is greater than b. So in other words, CompareTo returns exactly the same values as are expected from the ICompare.Compare-function, hence CompareTo can be used to compare values easily in the Compare-function.

For example, the following statement:

return firstPage.Changed.CompareTo(secondPage.Changed);

Is identical with this:

if (firstPage.Changed.Equals(secondPage.Changed))
    return 0;
else
   return firstPage.Changed < secondPage.Changed ? -1 : 1;

EPiTrace logger