2

How can I sort an ArrayList of objects? I have implemented the IComparable interface while sorting the ArrayList, but I am not getting the required result.

My code sample:

public class Sort : IComparable
{
    public string Count { get; set; }
    public string Url { get; set; }
    public string Title { get; set; }

    public int CompareTo(object obj)
    {
        Sort objCompare = (Sort)obj;
        return (this.Count.CompareTo(objCompare.Count));
    }
}

Here I want to sort the ArrayList based on Count.

Samuel Slade
  • 8,405
  • 6
  • 33
  • 55
Srikanth
  • 683
  • 3
  • 16
  • 23
  • 1
    @Srikanth Tell us which .NET version you're using for your development :) (re-tag your question for this). – Matías Fidemraizer Jan 30 '12 at 13:32
  • 6
    "i am not getting the required result" is not enough information. Please read http://tinyurl.com/so-hints and update your question. Also, do you *have* to use `ArrayList` rather than `List`? Non-generic collections are, like, so 2004. – Jon Skeet Jan 30 '12 at 13:34
  • What result do you get and what do you expect? – jeroenh Jan 30 '12 at 13:35
  • 4
    "string Count" : potential defect. "11" comes before "3" – Amy B Jan 30 '12 at 13:39

3 Answers3

3

try this:

public class Sort : IComparable<Sort>
{
    public string Count { get; set; }
    public string Url { get; set; }
    public string Title { get; set; }

    public virtual int CompareTo(Sort obj)
    {
        return (Count.CompareTo(obj.Count));
    }
}

as Count is string, it may not sort the way you expect....

Stig
  • 1,323
  • 16
  • 22
0

According to the MSDN documentation:

To perform a stable sort, you must implement a custom IComparer interface to use with the other overloads of this method.

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
0

Or you can just use a LINQ construct to get a sorted version of your list, like so:

var results = myArrayList.OrderBy(x => x.Count).ToList();

Is there a reason you are not using LINQ (yet)?

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
  • This doesn't compile and gives the error `Error CS1061 'ArrayList' does not contain a definition for 'OrderBy' and no accessible extension method 'OrderBy' accepting a first argument of type 'ArrayList' could be found (are you missing a using directive or an assembly reference?)` – Matthew Lock Feb 21 '22 at 12:39
  • See correct answer here https://stackoverflow.com/a/852490/74585 – Matthew Lock Feb 21 '22 at 12:42