Welcome to SofiaDev.Org's Blogs Sign in | Join | Help

Comparing and Sorting with Generics

I’m working on a project on which I need to sort some custom classes. Today, I’ve decided to play around and find easier and faster way to deal with different sorting scenarios with the use of generics.

I’ve a simple class hierarchy with a root abstract class called DataObject. From there I’ve inherited with a number of implementation classes that are used as a data containers (I’m using nHibernate for accessing the data in my MS SQL database).

I need to be able to sort arrays of instances of my data container classes. Some of them by a property A, and other by property B. Property A and B might have different types (string and int for example), and I don’t want to write a number of IComparer implementations.

So, I wrote that:

using System;
using System.Collections;

namespace SofiaDev.Generic
{
      public abstract class DataObjectSortableBy<T> : DataObject, IComparer where T : IComparable<T>
      {
            protected abstract T SortOnThisField
            {
                  get;
            }

            public virtual int Compare(object o1, object o2)
            {
                  T t1 = ((DataObjectSortableBy<T>)o1).SortOnThisField;
                  T t2 = ((DataObjectSortableBy<T>)o2).SortOnThisField;

                  if (null != t1 && null == t2)
                        return 1;
                  if (null == t1 && null != t2)
                        return -1;
                  if (null == t1 && null == t2)
                        return 0;

                  return t1.CompareTo(t2);
            }           

            public abstract object Empty
            {
                  get;
            }
      }
}

Now I can define base abstract classes for sorting.
Like this:

namespace SofiaDev.Generic
{
      public abstract class DataObjectSortableByString : DataObjectSortableBy<string>
      {

      }

      public abstract class DataObjectSortableByInt : DataObjectSortableBy<int>
      {

      }
}

 

And then inherit from them and oiverride the SortOnThisField method.

.NET RULEZ :)

Published 26 Април 2006 14:06 by branimir

Comments

No Comments

Anonymous comments are disabled