IComparer doesn't work

T

Tony Johansson

Hello!

I have this ProductComparerCount class below that compare the
count field for the Product class.
The collection class is named myProdList and is defined like this
List<Product> myProdList = new List<Product>();

The actual sort command look like this
myProdList.Sort(ProductComparerCount.Default);

I can't use the IComparable(CompareTo) because I have some other sorting
also.

Now to my problem when I compile I get the following 2 error
The second error is probably a consequence of the first.
Error 1 The best overloaded method match for
'System.Collections.Generic.List<MediaShop.Product>.Sort(System.Collections.Generic.IComparer<MediaShop.Product>)'
has some invalid arguments F:\C#\Ovningar\MediaShop\Statistik.cs 57 10
MediaShop

Error 2 Argument '1': cannot convert from 'System.Collections.IComparer' to
'System.Collections.Generic.IComparer<MediaShop.Product>'
F:\C#\Ovningar\MediaShop\Statistik.cs 57 33 MediaShop

How can I fix this. I can't understand where I have done any misstake.

class ProductComparerCount : IComparer
{
public static IComparer Default = new ProductComparerCount();

public int Compare(object x, object y)
{
return Comparer.Default.Compare(
((Product)x).Count,((Product)y).Count);
}
}

//Tony
 
T

Tony Johansson

Hello!

I noticed that if I replaced this row
List<Product> myProdList = new List<Product>();
with this row
ArrayList myProdList = new ArrayList();
it worked

So why doesn't support the IComparer to sort generic list ?

//Tony
 
T

Tony Johansson

Hello!

Here is the correct version

class ProductComparerCount : IComparer<Product>
{
public int Compare(Product x, Product y)
{
return y.Count - x.Count;}
}
 
J

Jesse Houwing

Hello Tony,
Hello!

I noticed that if I replaced this row
List<Product> myProdList = new List<Product>();
with this row
ArrayList myProdList = new ArrayList();
it worked
So why doesn't support the IComparer to sort generic list ?

You need to use the generic version of IComparer,

So implement IComparer<Product> and it should work.

Jesse
 

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