Sort an ArrayList of Objects in C#

血红的双手。 提交于 2019-12-02 14:24:51

问题


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.


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/9064636/sort-an-arraylist-of-objects-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!