Search code examples
c#arraylistsortingicomparable

Sort an ArrayList of Objects in C#


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.


Solution

  • 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....