Thursday, October 23, 2014

Sorting a list of custom object in C#

Sorting a list of custom tyupe is not as simple as sorting a list of integers and strings for example. The type needs to be made IComparable and a CompareTo method needs to be added to allow the default .Sort method to work correctly.
var menuItems = new List<MenuItem>();

// add items

menuItems.sort();
public class MenuItem : IComparable<MenuItem>
{
    public int MenuID { get; set; }
    public int ParentID { get; set; }
    public string Title { get; set; }
    public string URL { get; set; }
    public int SortOrder { get; set; }

    public int CompareTo(MenuItem other)
    {
        return this.SortOrder.CompareTo(other.SortOrder);
    }
}
The example above shows the MenuType class being made IComparable with itself and the CompareTo method is comparing based on the sort order. In this example the list of MenuItems will be sorted by that SortOrder field.

No comments:

Post a Comment