Generic.IComparer question

I

INeedADip

I am trying to use the following generic (reflection) class as the
ICamparer parameter for 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();
oList.Sort(New GenericComparer("QueueName"));

This is my GenericComparer:

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);
}
}

Hopefull you can see where I'm trying to go with this. Any
suggestions? Am I approaching this the wrong way?
 
?

=?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?=

INeedADip said:
I am trying to use the following generic (reflection) class as the
ICamparer parameter for 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();
oList.Sort(New GenericComparer("QueueName"));

This is my GenericComparer:

public class GenericComparer : IComparer


Try defining it as:

public class GenericComparer<T> : IComparer<T>, IComparer
(+ some changes to the method definition, etc., also note that I listed
both the generic version and the non-generic version so that it can be
used with non-generic collections as well)

Since you do the manual work inside you're not actually gaining anything
by defining it like this, but it would be compatible with the
requirements of the Sort method, which would then be called like this:

oList.Sort(new GenericComparer<AccountDB.Queue>("QueueName"));

Note that this is off the top of my head so test it and yell at me if I
got it wrong :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top