首页 > 解决方案 > 排序列表包括按日期的日期值

问题描述

我正在开发一个打卡程序,但在让我的打卡时间按正确顺序时遇到了问题。日期是按顺序排列的,但 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;
   }
  }

标签: c#

解决方案


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()(您可以通过覆盖自定义类来使其变得非常简单。)


推荐阅读