按日期对包含日期值的List <string>进行排序

时间:2018-12-20 15:17:50

标签: c#

我正在开发一个时钟程序,但是我的时间安排在正确的顺序时遇到了问题。日期是有序的,但是list.Sort()使时间混乱了。它像字符串一样对它进行排序,这很有意义,因为它是字符串。 3:41 PM在7:20 AM之前进行排序,因为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());
}

我将“%”放入其中,以便稍后可以在%处分割字符串,以在打卡时间中插入打卡时间,打卡类型,所需的批准和批准。

我的问题是如何按日期和时间对字符串进行排序?

EDIT

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;
   }
  }

1 个答案:

答案 0 :(得分:7)

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()来使其变得非常简单。)

相关问题