1

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

1 Answer 1

5

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; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.