Question

I'm trying for hours to sort an ArrayList using IComparable...

Please note that I cant use IComparer to do this.

Here is the code :

class Pays : IComparable<Pays>
{
    private string nomPays;

    public string NomPays{get{return nomPays;}set{nomPays = value;}}

    public int CompareTo(object x)
    {
        Pays myX = (Pays)x;
        return string.Compare(this.nomPays, x.nomPays);
    }
}

class TestPays
{
    public static ArrayList LireRemplirPays(){ //...blabla
        return uneListe;
    }
    static void Main(string[] args){
        ArrayList paysList = LireRemplirPays();
        paysList.Sort();          
    }
}

Error paste : System.ArgumentException: At least one object must implement IComparable System.Collections.Comparer.Compare(Object a, Object b)......

What can I do ? thanks for reading

Edit :

So my first mistake was :

class Pays : IComparable<Pays>

instead of

class Pays : IComparable

second mistake :

return nomPays.CompareTo(myX.nomPays);
Was it helpful?

Solution

You should use a generic list instead of an ArrayList:

class TestPays
{
    public static List<Pays> LireRemplirPays() { //...blabla
        return uneListe; // Cast here if necessary
    }
    static void Main(string[] args) {
        List<Pays> paysList = LireRemplirPays();
        paysList.Sort();          
    }
}

ArrayList isn't generic and could contain any type of object, and object doesn't implement IComparable.

Also, if NomPays doesn't actually do any checking, you can use the shorthand and not have to explicitly declare a backing field:

public string Nom { get; set; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top