Comparing Objects


I’m hoping there’s a better way to do this, and I just missed that class, but until that day, I’ve created this: GenericComparer

Implementation


    public class GenericComparer<T> : IComparer<T>
    {
        private string FieldName
        {
            get;
            set;
        }

        private PropertyInfo CompareProperty
        {
            get;
            set;
        }

        public GenericComparer(string fieldName)
        {
            this.FieldName = fieldName;
            this.CompareProperty = typeof(T).GetProperty(fieldName);
        }

        public int Compare(T x, T y)
        {
            if (this.CompareProperty == null)
            {
                return 0;
            }

            var xValue = this.CompareProperty.GetValue(x, null);
            var yValue = this.CompareProperty.GetValue(y, null);

            if (xValue == null && yValue == null)
            {
                return 0;
            }

            if (xValue != null && xValue is IComparable)
            {
                return ((IComparable)xValue).CompareTo(yValue);
            }
            else if (yValue != null && yValue is IComparable)
            {
                return -1 * ((IComparable)yValue).CompareTo(xValue);
            }
            else if (xValue == yValue)
            {
                return 0;
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
    }

Usage

   List list = dataFactory.GetGenericListFromSomewhereAwesome();
   list.Sort(new GenericComparer("CustomID"));

This seems to work in limited circumstances, and is “good enough” for now.  Any suggestions improvements/alternate methods would be awesome and greatly appreciated.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s