首页 > 解决方案 > 使用 C# 对 ArrayList 中的 2 个数字进行排序?

问题描述

我正在使用 ArrayList 来存储名为 SocialTimes 的类的对象。SocialTimes 包含一个字符串和 2 个数字。我正在尝试根据小时和分钟进行排序。我不知道该怎么做。有人能帮我吗?

public class SocialTimes
{
    string DateToPostStr = "";
    int HourToPost = 0;
    int MinuteToPost = 0;

    public SocialTimes(string DateToPostStr, int HourToPost, int MinuteToPost)
    {
        this.DateToPostStr = DateToPostStr;
        this.HourToPost = HourToPost;
        this.MinuteToPost = MinuteToPost;
    }

    public string getDateToPostStr()
    {
        return this.DateToPostStr;
    }

    public int getHourToPost()
    {
        return this.HourToPost;
    }

    public int getMinuteToPost()
    {
        return this.MinuteToPost;
    }

    public static implicit operator SocialTimes(ArrayList v)
    {
        throw new NotImplementedException();
    }
}


public class myComparer : IComparer
{
    int IComparer.Compare(Object xx, Object yy)
    {
        SocialTimes x = (SocialTimes)xx;
        SocialTimes y = (SocialTimes)yy;
        return x.getHourToPost().CompareTo(y.getHourToPost());
    }
}

所以这里有一个测试排序ArrayList的方法...

    private void testHourMinuteSort()
    {
        ArrayList projects = new ArrayList();
        projects.Add(new SocialTimes("03/14/20", 17, 7));
        projects.Add(new SocialTimes("03/14/20", 10, 39));
        projects.Add(new SocialTimes("03/14/20", 12, 7));
        projects.Add(new SocialTimes("03/14/20", 3, 16));
        projects.Add(new SocialTimes("03/14/20", 21, 8));
        projects.Add(new SocialTimes("03/14/20", 20, 56));
        projects.Add(new SocialTimes("03/14/20", 3, 2));
        projects.Sort(new myComparer());
        string hoursminutes = "";

        foreach (SocialTimes item in projects)
        {
            hoursminutes = hoursminutes + String.Format("Hour: {0} Minute: {1}", item.getHourToPost(), item.getMinuteToPost()) + Environment.NewLine;
        }

        MessageBox.Show(hoursminutes);
    }

小时分钟:

我需要按小时和分钟排序,如下所示。

标签: sortingarraylist

解决方案


将值转换为分钟并进行比较,而不仅仅是小时。

int x1 = t1.Hours * 60 + t1.Minutes;

就像现在一样,具有相同(整)小时数的时间将相对于彼此“随机”排序,因为不比较分钟。

或者,只需使用 LINQ 和类似的东西:

s.OrderBy(x => x.Hours).ThenBy(x => x.Minutes)

使用表示日期和/或时间范围的日期和/或时间跨度可能会更清楚。在这种情况下,上述代码将被简化为只比较一个值。

使用适当的泛型集合类型,例如 List<SocialTimes> 也是处理集合的更现代和类型安全的方法。


推荐阅读