473,398 Members | 2,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

IComparer Question

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?

Jan 6 '06 #1
10 2809
INeedADip <in*******@gmail.com> wrote:
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


You've implemented System.Collections.IComparer. You need to implement
System.Collections.Generic.IComparer<T>.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 6 '06 #2
Hi,

You get this error because your GenericComparer implements IComparer not
IComparer<T>. Despite the same name both interfaces are different.

If you look at the Sort method of List<T> generic you'll see that it is
declared as

public void Sort (
IComparer<T> comparer
)You need to declare you comparer aspublic class GenericComparer :
IComparer<[the type of the elements in the list]>or you can create generic
comparer and specify the type of the elements upon creation.-- HTHStoitcho
Goutsev (100)"INeedADip" <in*******@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
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?

Jan 6 '06 #3
Any ideas on how I should approach this?

I thought maybe IComparer<object> but I can't quite get it to work..

Jan 7 '06 #4
INeedADip <in*******@gmail.com> wrote:
Any ideas on how I should approach this?

I thought maybe IComparer<object> but I can't quite get it to work..


Make your comparer generic as well. Something like (untested):

public class GenericComparer<T> : IComparer<T>
{
string propertyName;

public GenericComparer(string propertyName)
{
this.propertyName = propertyName;
}

public int Compare(T x, T 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);
}
}

Note that I'm still using GetType() in the above rather than typeof(T)
in case the properties aren't provided by T itself, but by a class
derived from T.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 7 '06 #5
Instead of creating an implementation of IComparer<T>, you can just use
anonymous delegates as well (unless you need to use this implementation in a
good number of places).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"INeedADip" <in*******@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
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?

Jan 7 '06 #6
Jon Skeet - Thank you very much for the help.
I'm sure there are better ways of doing this, but this seems like a pretty
good way to sort my objects (without making a bunch of IComparer<T>
classes).
I wanted to post the final solution here incase anyone else is looking for
something similar, it sure would have saved me a lot of time.

This will allow you to sort on a List<T> of custom classes with simple value
type properties:

public enum GenericComparerSortDirection { Asc, Desc }

public class GenericComparer<T> : IComparer<T>
{

private string propertyName;
private GenericComparerSortDirection theDirection;

public GenericComparer(string propertyName,
GenericComparerSortDirection eSortDirection)
{
this.propertyName = propertyName;
this.theDirection = eSortDirection;
}

public int Compare(T x, T 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 make the comparsion
if (this.theDirection == GenericComparerSortDirection.Asc)
return ((IComparable)valueOfX).CompareTo(valueOfY);
else
return ((IComparable)valueOfY).CompareTo(valueOfX);
}
}

Usage:

List<MyClass> lstSorted = getABunchOfObjects();
lstSorted.Sort(new GenericComparer<MyClass>("PropertyName",
GenericComparerSortDirection.Asc));

--------
Someone with a blog should post this for others.
Jan 8 '06 #7
Thank you very much for the help.
I'm sure there are better ways of doing this, but this seems like a
pretty good way to sort my objects (without making a bunch of
IComparer<T> classes).
I wanted to post the final solution here incase anyone else is looking
for something similar, it sure would have saved me a lot of time.

This will allow you to sort on a List<T> of custom classes with simple
value type properties:

public enum GenericComparerSortDirection { Asc, Desc }

public class GenericComparer<T> : IComparer<T>
{

private string propertyName;
private GenericComparerSortDirection theDirection;

public GenericComparer(string propertyName,
GenericComparerSortDirection eSortDirection)
{
this.propertyName = propertyName;
this.theDirection = eSortDirection;
}

public int Compare(T x, T 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 make the comparsion
if (this.theDirection == GenericComparerSortDirection.Asc)
return ((IComparable)valueOfX).CompareTo(valueOfY);
else
return ((IComparable)valueOfY).CompareTo(valueOfX);
}
}

Usage:

List<MyClass> lstSorted = getABunchOfObjects();
lstSorted.Sort(new GenericComparer<MyClass>("PropertyName",
GenericComparerSortDirection.Asc));

--------
Someone with a blog should post this for others.

Jan 8 '06 #8
Thank you very much for the help.
I'm sure there are better ways of doing this, but this seems like a
pretty good way to sort my objects (without making a bunch of
IComparer<T> classes).
I wanted to post the final solution here incase anyone else is looking
for something similar, it sure would have saved me a lot of time.

This will allow you to sort on a List<T> of custom classes with simple
value type properties:

public enum GenericComparerSortDirection { Asc, Desc }

public class GenericComparer<T> : IComparer<T>
{

private string propertyName;
private GenericComparerSortDirection theDirection;

public GenericComparer(string propertyName,
GenericComparerSortDirection eSortDirection)
{
this.propertyName = propertyName;
this.theDirection = eSortDirection;
}

public int Compare(T x, T 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 make the comparsion
if (this.theDirection == GenericComparerSortDirection.Asc)
return ((IComparable)valueOfX).CompareTo(valueOfY);
else
return ((IComparable)valueOfY).CompareTo(valueOfX);
}
}

Usage:

List<MyClass> lstSorted = getABunchOfObjects();
lstSorted.Sort(new GenericComparer<MyClass>("PropertyName",
GenericComparerSortDirection.Asc));

--------
Someone with a blog should post this for others.

Jan 8 '06 #9
I did think about that, but I use it so often, this was a better way...

Jon Skeet - Thank you very much for the help.
I'm sure there are better ways of doing this, but this seems like a
pretty good way to sort my objects (without making a bunch of
IComparer<T> classes).
I wanted to post the final solution here incase anyone else is looking
for something similar, it sure would have saved me a lot of time.

This will allow you to sort on a List<T> of custom classes with simple
value type properties:

public enum GenericComparerSortDirection { Asc, Desc }

public class GenericComparer<T> : IComparer<T>
{

private string propertyName;
private GenericComparerSortDirection theDirection;

public GenericComparer(string propertyName,
GenericComparerSortDirection eSortDirection)
{
this.propertyName = propertyName;
this.theDirection = eSortDirection;
}

public int Compare(T x, T 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 make the comparsion
if (this.theDirection == GenericComparerSortDirection.Asc)
return ((IComparable)valueOfX).CompareTo(valueOfY);
else
return ((IComparable)valueOfY).CompareTo(valueOfX);
}
}

Usage:

List<MyClass> lstSorted = getABunchOfObjects();
lstSorted.Sort(new GenericComparer<MyClass>("PropertyName",
GenericComparerSortDirection.Asc));

--------
Someone with a blog should post this for others.

Jan 9 '06 #10
For reference or any more discussion:

http://ineedadip.blogspot.com/2006/0...icomparer.html

Feb 1 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Cybertof | last post by:
Hello, Could someone please explain me the difference between the 2 interfaces IComparable and IComparer ? In which cases use one or the other ? Are they dedicated to own classes or built-in...
1
by: INeedADip | last post by:
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...
11
by: solandre | last post by:
my motivation is as follows: i have to binarysearch several million times an long that is several million items big. this costs time, although i use Array.Binarysearch<long>. so i try to keep...
4
by: christriddle | last post by:
Hi, I want to be able to sort a ArrayList of Points, for example, in one of two (or more) ways depending of the nature of the Points in the ArrayList. Basically I want two different comparers,...
1
by: Brett Romero | last post by:
What are the reasons to use one over the other? SortedList implements IComparer.Compare(). Why would you also want to create a SortedList class that implements IComparable.CompareTo()? I know...
3
by: jtfaulk | last post by:
Re: ArrayList, Sort, Menu, IComparer, Object, multidemensional I have a multi-dimensional arraylist, and I would like to sort one level of it but not all. The multi-dimensional arraylist...
10
by: Tony | last post by:
Hello! I'm reading in a book and this can't be correct it says. "Objects passed to Comparer.Compare() are checked to see if they support IComparable. If they do, then that implementation is...
3
by: raylopez99 | last post by:
This is an example of using multiple comparison criteria for IComparer/ Compare/CompareTo for List<and Array. Adapted from David Hayden's tutorial found on the net, but he used ArrayList so the...
5
by: xtech1005 | last post by:
This is probably a newbie question but I'm really confused on how the IComparer works and I've looked for information online and offline. The code works, I just don't understand how. I'm sorting...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.