I
INeedADip
I am trying to use a generic (reflection) IComparer class to sort a
generic list but I get the error:
Unable to cast object of type 'GenericComparer' to type
'System.Collections.Generic.Icomparer `1[AccountDB.Queue]'
My code looks like the following:
List<AccountDB.Queue> oList = getAllQueuesFunction();
List.Sort(New GenericComparer("QueueName")); <-- Error
My class looks like:
public class GenericComparer : IComparer
{
string propertyName;
public GenericComparer(string propertyName)
{
this.propertyName = propertyName;
}
public int Compare(object x, object y)
{
// gets the value of the x property
PropertyInfo property =
x.GetType().GetProperty(propertyName);
object valueOfX = property.GetValue(x, null);
// gets the value of the y property
property = y.GetType().GetProperty(propertyName);
object valueOfY = property.GetValue(y, null);
// now makes the comparsion
return ((IComparable)valueOfX).CompareTo(valueOfY);
}
}
Hopefully you can see what I am trying to accomplish. Am I approaching
this the wrong way? Any suggestions or Comments?
generic list but I get the error:
Unable to cast object of type 'GenericComparer' to type
'System.Collections.Generic.Icomparer `1[AccountDB.Queue]'
My code looks like the following:
List<AccountDB.Queue> oList = getAllQueuesFunction();
List.Sort(New GenericComparer("QueueName")); <-- Error
My class looks like:
public class GenericComparer : IComparer
{
string propertyName;
public GenericComparer(string propertyName)
{
this.propertyName = propertyName;
}
public int Compare(object x, object y)
{
// gets the value of the x property
PropertyInfo property =
x.GetType().GetProperty(propertyName);
object valueOfX = property.GetValue(x, null);
// gets the value of the y property
property = y.GetType().GetProperty(propertyName);
object valueOfY = property.GetValue(y, null);
// now makes the comparsion
return ((IComparable)valueOfX).CompareTo(valueOfY);
}
}
Hopefully you can see what I am trying to accomplish. Am I approaching
this the wrong way? Any suggestions or Comments?