c# - 排序列表包括按日期的日期值
问题描述
我正在开发一个打卡程序,但在让我的打卡时间按正确顺序时遇到了问题。日期是按顺序排列的,但 list.Sort() 将时间打乱了。它像字符串一样对其进行排序,这是有道理的,因为它是一个字符串。3:41PM 在 7:20AM 之前排序,因为 3 在 7 之前。请参见示例:
12/17/2018 3:41:00 PM Clock Out Yes BB
12/17/2018 7:20:00 AM Clock In NO Not Needed
由于我将信息转储到列表中,我不确定如何完成此操作。
while (reader.Read())
{
timeClockDataList.Add(reader["Punch"].ToString() + "%" + reader["PunchType"].ToString() + "%" + reader["NeedsApproval"].ToString() + "%" + reader["Approval"].ToString());
}
我将“%”放在那里,以便稍后在 % 处拆分字符串,以便在时间卡中填充打卡时间、打卡类型、需要的批准和批准。
我的问题是如何按日期和时间对该字符串进行排序?
编辑
while (reader.Read())
{
timeClockDataList.Add(new ClockData
{
Punch = DateTime.Parse(reader["Punch"].ToString()),
PunchType = reader["PunchType"].ToString(),
NeedsApproval = reader["NeedsApproval"].ToString(),
Approval = reader["Approval"].ToString(),
});
//***This is the old code that makes one long string***
//timeClockDataList.Add(reader["Punch"].ToString() + "%" + ToString() + +
}
timeClockDataList.OrderBy(x => x.Punch);
//***This is the old code that would sort the list string***
//timeClockDataList.Sort();
using (StreamWriter writer = new StreamWriter(filePath, true))
{
for (int _i = 0; _i < timeClockDataList.Count; ++_i)
{
punch = timeClockDataList[_i].Punch.ToString();
punchType = timeClockDataList[_i].PunchType;
needsApproval = timeClockDataList[_i].NeedsApproval;
approval = timeClockDataList[_i].Approval;
writer.WriteLine(String.Format("{0,-5}{1,-30}{2,-20}{3,-11}{4,-15}", " ", punch, punchType, needsApproval, approval));
punch = null;
punchType = null;
needsApproval = null;
approval = null;
}
}
解决方案
timeClockDataList
是错误的类型。当一切都是一个大字符串时,您没有数据,您只有一个大字符串。
制作一个自定义对象来存储您的数据。例如:
class ClockData
{
public DateTime Punch { get; set; }
public string PunchType { get; set; }
// etc.
}
将您的数据读入该类的列表:
while (reader.Read())
{
timeClockDataList.Add(new ClockData
{
Punch = DateTime.Parse(reader["Punch"].ToString()),
PunchType = reader["PunchType"].ToString(),
// etc.
});
}
现在您有了实际数据,可以对其进行操作/排序/等。容易地:
timeClockDataList.OrderBy(x => x.Punch)
您可能还想在填充它时进行一些错误检查,TryParseExact
用于DateTime
等。您可以进行各种改进。最终,当您想要显示数据时,就是将其输出为字符串。.ToString()
(您可以通过覆盖自定义类来使其变得非常简单。)
推荐阅读
- javascript - 打字稿-“调试器;” 在 Angular 中使用 QA 环境时语句不起作用
- sql-server - TFS 2018 需要哪个版本的 SQL Server 2016?
- .net - 如何在 Visual Studio 中为术语提供上下文?
- python - 作业调度:使用 while(1) 和 time.sleep()
- c++ - 无效使用非静态数据成员错误
- android - 如果显示 toast 是否可以返回 true
- c++ - 静态库转换为共享库符号是否隐藏?
- javascript - 在我的 javascript 函数中使用生成的请求作为变量
- python - 使用 Python 的 Flask 和 jsonpickle 在 JSON 中获取不需要的转义字符
- python - 如何在抓取之前从数据库中获取 url 和 row id 以在管道中使用它来存储数据?