I have the following code to compare two collections to one another...
//code invocation
CollectionComparer comp = new CollectionComparer("name", "ASC");
this.InnerList.Sort(comp);
class
public class CollectionComparer : IComparer
{
private String _property;
private String _order;
public CollectionComparer(String Property, String Order)
{
this._property = Property;
this._order = Order;
}
public int Compare(object obj1, object obj2)
{
int returnValue;
Type type = obj1.GetType();
PropertyInfo propertie1 = type.GetProperty(_property); // returns null here
Type type2 = obj2.GetType();
PropertyInfo propertie2 = type2.GetProperty(_property); // returns null here
object finalObj1 = propertie1.GetValue(obj1, null); // Null Reference Exception thrown here, because propertie1 is null
object finalObj2 = propertie2.GetValue(obj2, null);
IComparable Ic1 = finalObj1 as IComparable;
IComparable Ic2 = finalObj2 as IComparable;
if (_order == "ASC")
{
returnValue = Ic1.CompareTo(Ic2);
}
else
{
returnValue = Ic2.CompareTo(Ic1);
}
return returnValue;
}
}
The code seems to work fine, except when I try to sort a property called "name". When comparing that property both the variables propertie1
and propertie2
are null, and the code throws an exception because of that.
So my question is how to use reflection to get the value of a property with the name of "name"?