Geek Noise
Rants, rambles, news and notes by Peter Provost
28

Generic Property Comparer Class

Friday, 28 February 2003 04:53 by Peter Provost

In a previous post, Justin and I were discussing the idea of having a generic object comparer. Well this morning I busted one out. Here it is. Enjoy!

public class GenericClassComparer : IComparer

{

public GenericClassComparer( System.Type objectType, string propertyName )

{

LoadPropertyInfo( objectType, propertyName );

}


private
void LoadPropertyInfo( System.Type objectType, string propertyName )

{

MemberInfo[] members = objectType.GetMember( propertyName,

MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance );


if
( members.Length > 0 )

{

MemberInfo member = members[0];

if( member is PropertyInfo )

_pi = (PropertyInfo) member;

}

}


public
int Compare( object o1, object o2 )

{

if( _pi == null )

throw new ArgumentException("Invalid property name specified.");


object
val1 = _pi.GetValue( o1, null );

object val2 = _pi.GetValue( o2, null );


if
( val1 is IComparable )

{

IComparable c1 = (IComparable) val1;

IComparable c2 = (IComparable) val2;

return c1.CompareTo(c2);

}


return
0;

}


private
PropertyInfo _pi = null;

}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   Technology
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed