Created
February 27, 2010 05:22
-
-
Save mdeiters/316493 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ObjectComparer : System.Collections.IComparer | |
{ | |
private const int COMPARE_EQUAL = 0; | |
private const int COMPARE_GREATERTHAN = 1; | |
private const int COMPARE_LESSTHAN = -1; | |
private string _propertyNames = string.Empty; | |
//params string[] names | |
public ObjectComparer(string propertyName){ | |
this._propertyNames = propertyName; | |
} | |
public int Compare(object x, object y){ | |
object a = x.GetType().GetProperty(this._propertyNames).GetValue(x, null); | |
object b = y.GetType().GetProperty(this._propertyNames).GetValue(y, null); | |
bool aIsNotNothing = a != null; | |
bool bIsNotNothing = b != null; | |
bool notSameType = a.GetType() == b.GetType(); | |
if(aIsNotNothing && !bIsNotNothing){ | |
return COMPARE_GREATERTHAN; | |
} | |
else if(!aIsNotNothing && bIsNotNothing){ | |
return COMPARE_LESSTHAN; | |
} | |
else if(!aIsNotNothing && !bIsNotNothing){ | |
return COMPARE_EQUAL; | |
} | |
else if(notSameType){ | |
return COMPARE_LESSTHAN; | |
} | |
if (a is System.IComparable){ | |
return (a as System.IComparable).CompareTo(b); | |
} | |
else{ | |
throw new InvalidOperationException(a.GetType().Name + " is not supported by the ObjectComparer."); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MultiKeyObjectComparer : System.Collections.IComparer | |
{ | |
private ObjectComparer[] _comparers; | |
public MultiKeyObjectComparer(params string[] propertyNames){ | |
this._comparers = this.CreateComparers(propertyNames); | |
} | |
private ObjectComparer[] CreateComparers(string[] propertyNames){ | |
System.Collections.ArrayList list = new System.Collections.ArrayList(); | |
foreach(string propertyName in propertyNames){ | |
list.Add(new ObjectComparer(propertyName)); | |
} | |
return (list.ToArray(typeof(ObjectComparer)) as ObjectComparer[]); | |
} | |
public int Compare(object x, object y){ | |
int comparison = 0; | |
foreach(ObjectComparer comparer in this._comparers){ | |
comparison = comparer.Compare(x, y); | |
if(comparison != 0) | |
{ | |
return comparison; | |
} | |
} | |
return comparison; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment