Click here to Skip to main content
Licence CPOL
First Posted 1 Nov 2006
Views 16,722
Bookmarked 15 times

Simple PropertyComparer

By | 1 Nov 2006 | Article
A Simple PropertyComparer

Introduction

This article is about a simple PropertyComparer class that can be used to sort collections of objects by property of the objects in the collection:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI.WebControls;

namespace yourNamespace
{
    public class PropertyComparer<T> : IComparer<T>
    {
        private PropertyInfo property;
        private SortDirection sortDirection;

        public PropertyComparer(string sortProperty, SortDirection sortDirection)
        {
            property = typeof (T).GetProperty(sortProperty);
            Utils.AssertIsNotNull(
                string.Format("Property {0} not found on type {1}", sortProperty,
                              typeof (T).FullName), sortProperty);
            this.sortDirection = sortDirection;
        }

        public int Compare(T x, T y)
        {
            object valueX = property.GetValue(x, null);
            object valueY = property.GetValue(y, null);
            
            if (sortDirection == SortDirection.Ascending)
            {
                return Comparer.Default.Compare(valueX, valueY);
            }
            else
            {
                return Comparer.Default.Compare(valueY, valueX);
            }
        }
    }
}

Usage

Here is an example of using the PropertyComparer to sort a collection of objects:

    public class ObjectInCollectionType
    {
        private string text = Guid.NewGuid().ToString();

        public string Text
        {
            get { return text; }
            set { text = value; }
        }
    }
    public class TestPropertyComparer
    {
        public static void Test()
        {
            List<ObjectInCollectionType> myList = new List<ObjectInCollectionType>();
            myList.Add(new ObjectInCollectionType());
            myList.Add(new ObjectInCollectionType());
            myList.Add(new ObjectInCollectionType());
            myList.Add(new ObjectInCollectionType());
            // Sorting the collection
            myList.Sort(new PropertyComparer<ObjectInCollectionType>
                ("Text", SortDirection.Ascending));
        }
    }

Happy programming.

History

  • 1st November, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ion Botnari

Web Developer

Moldova (Republic Of) Moldova (Republic Of)

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralComparer.Compare() throws an exception if none of the arguments impements IComparable PinmemberTheo Bebekis1:42 23 Jul '09  
GeneralGood idea, but there's a better way Pinmemberkma24813:40 15 Nov '06  
GeneralRe: Good idea, but there's a better way PinmemberTheo Bebekis1:36 23 Jul '09  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 1 Nov 2006
Article Copyright 2006 by Ion Botnari
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid