sorting - 使用 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);
}
小时分钟:
- 小时:3 分钟:16
- 小时:3 分钟:2
- 小时:10 分钟:39
- 小时:12 分钟:7
- 小时:17 分钟:7
- 小时:20 分钟:56
- 小时:21 分钟:8
我需要按小时和分钟排序,如下所示。
- 小时:3 分钟:2
- 小时:3 分钟:16
- 小时:10 分钟:39
- 小时:12 分钟:7
- 小时:17 分钟:7
- 小时:20 分钟:56
- 小时:21 分钟:8
解决方案
将值转换为分钟并进行比较,而不仅仅是小时。
int x1 = t1.Hours * 60 + t1.Minutes;
就像现在一样,具有相同(整)小时数的时间将相对于彼此“随机”排序,因为不比较分钟。
或者,只需使用 LINQ 和类似的东西:
s.OrderBy(x => x.Hours).ThenBy(x => x.Minutes)
使用表示日期和/或时间范围的日期和/或时间跨度可能会更清楚。在这种情况下,上述代码将被简化为只比较一个值。
使用适当的泛型集合类型,例如 List<SocialTimes> 也是处理集合的更现代和类型安全的方法。
推荐阅读
- java - 日志中经常看到的Kafka FETCH_SESSION_ID_NOT_FOUND
- json - 如何使用 global.asa 文件中的 javascript 从本地 json 文件中读取 json 数组?
- python - 未知时间增量/日期时间格式
- javascript - 如何以角度导入外部javascript库?
- javascript - 我怎样才能让这个 If 语句返回 true?
- javascript - 如何在旁边的跨度中显示“数字类型输入”的值
- c# - 在 IIS 上运行的 ASP.Net WebAPI 应用程序上出现间歇性 NullReferenceException
- javascript - 如何显示图表中每个点的 Y 轴刻度
- android - Android 10 (Q) 中主栏的高度
- javascript - 如何让视频通过鼠标悬停播放和暂停并使用 getElementsByTagName 设置模糊