Sorting Generic.List Items

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);
    }
}


You might also enjoy these related posts

  1. An example on how to format file size in C# Thank you Fat Angus for having a post like this available for all to use.  I just happened to need a file size format routine, and Viola, Fat Angus has...
  2. A Simple Session State Item Manager for ASP.Net As I build applications there are times where I need to throw something into session state.  When I do so, I hate to have all the session state calls spread...
  3. Recursively populating a TreeView controls TreeNode collection Every now and then you come across a scenario where a Treeview control is the best solution for presenting a hierarchical view of data.  How do you populate the tree? ...
  4. Formatting the output of a phone number field I recently, in fact just now ran into an issue formatting a phone. So I don’t lose this info I’m writing this post. The problem was with formatting the phone...
  5. Serving Images on the Web – Correction for Dino’s article Hmm, the magazine editor seemed to have left some code out of the February post of ASP.Net Pro.  In Dino Esposito’s article  on how to serve up images on the...

About Wayne

Wayne John is a web developer in Southern California that shares his 25+ years of programming and web development experience freely and happily to anyone willing to learn. He also loathes speaking in the third person. If you enjoyed this post, make sure you subscribe to my RSS feed or get updates in your email.
This entry was posted in Web Development Tips and tagged , . Bookmark the permalink.

2 Responses to Sorting Generic.List Items

  1. Wayne says:

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

  2. Bitstar says:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv Enabled

Enter YourName @ YourKeywords in the Name field to take advantage of Keyword love. Please note, I normally won't approve comments that use products or niche keywords for a name. Get your comment approved, don't be a spammer.