Sorting Generic.List Items

January 15, 2008 · 2 comments

Great example of sorting a Generic.List collection of objects can be found here. For future reference for myself, here is a class that can be reused in future projects whenever I need to sort a collection of custom objects:

///

/// The generic comparer class allows for sorting on a generic collections property fields
/// 

/// An object
public class GenericComparer : IComparer
{
    ///

    /// Creates a new instance of the GenericComparer class
    /// 

    ///
A string expression of the field to sort
    ///
A SortDirection value to indicate     /// Ascending or Descending sort
    public GenericComparer(string sortExpression, SortDirection sortDirection)
    {
        this.SortExpression = sortExpression;
        this.SortDirection = sortDirection;
    }

    ///

    /// Private container for the Sort Direction
    /// 

    private SortDirection sortDirection;

    ///

    /// Private container for the expression used for the sort
    /// 

    private string sortExpression;

    ///

    /// The expression to use during the sort (in this case, the Generic objects field name)
    /// 

    public string SortExpression
    {
        get { return sortExpression; }
        set { sortExpression = value; }
    }

    ///

    /// The direction to perform the sort
    /// 

    public SortDirection SortDirection
    {
        get { return this.sortDirection; }
        set { this.sortDirection = value; }
    }

    ///

    /// Performs the sort on the supplied objects
    /// 

    /// 
    /// The following example shows how to implement and use this class:
    ///  items = MyDataObject.GetObjects();
    ///             items.Sort(new GenericComparer(SortExpression, SortDirection));
    ///         }
    ///     }
    /// ]]>
    /// 
    ///
The first object
    ///
The second object
    /// An int value that specifies the result of the comparison
    public int Compare(T x, T y)
    {
        PropertyInfo propertyInfo = typeof(T).GetProperty(SortExpression);
        IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
        IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);

        if (SortDirection == SortDirection.Ascending)
            return obj1.CompareTo(obj2);
        else
            return obj2.CompareTo(obj1);
    }
}

Wayne  (531 Posts)

Wayne John is a health coach for people that want to lose weight, gain weight, improve athletic performance, or simply maintain a healthy lifestyle. Wayne has lost over 55 pounds and improves his current health every day by using simple, straight-forward techniques that anyone can integrate into their lives to achieve the same. Contact Wayne today to realize your own health and fitness goals, or get started now by completing and submitting the free Wellness Profile. He also has been developing websites since 1995 and programming solutions for clients even longer. He'd rather be outside having fun in the sun though.


Start a discussion, or join in one

Thank you for taking the time to read this. I encourage people to speak their mind, so please feel free to leave a comment using the comment input form found below.

Bitstar

Thanks for the code. It saved me a ton of research today.

Wayne

Wow, that only took one year to help someone! hahaha, glad you found it useful.

Previous post:

Next post: