将日期的 string/xml 表示形式转换为 Date 类型,以便在 LINQ 中进行排序

Convert string/xml representation of date into Date type for sorting within LINQ

我正在将一些 XML 解析为自定义 Customer 对象,我需要按来自 XML 的日期 属性 对对象列表进行排序。由于日期值是一个字符串,我正在寻找一种快速方法将字符串值转换为日期,然后使用它进行排序,只要它不为空即可。

public class Customer 
{
  public string CustomerId { get; set; }
  public string JoinDate { get; set; }
}

List<Customer> customerList = xml.Descendants("data")
  .Select(x => new Customer
  {
    CustomerId = (x.Element("CUSTOMER_ID") != null) ? x.Element("CUSTOMER_ID").Value : string.Empty,
    JoinDate = (x.Element("JOIN_DATE") != null) ? x.Element("JOIN_DATE").Value : string.Empty
  }) 
  .GroupBy(x => x.CustomerId)
  .Select(x => x.First())
  .OrderBy(x => x.JoinDate)
  .ToList<Customer>();

到目前为止,我一直将 JoinDate 视为一个字符串,因为如果所有日期都在同一年,它仍然会排序。有没有一种快速的方法可以将日期从 string 转换为 date 以进行排序,请记住 date 的某些值可能为空或为空?

String 转换为 DateTime 的最快方法是使用 Convert.ToDateTime() 方法。您的字符串必须如下所示:"2018.01.05".

您的完整代码如下所示:

public class Customer 
{
  public string CustomerId { get; set; }
  public DateTime JoinDate { get; set; }
}

List<Customer> customerList = xml.Descendants("data")
  .Select(x => new Customer
  {
    CustomerId = (x.Element("CUSTOMER_ID") != null) ? x.Element("CUSTOMER_ID").Value : string.Empty,
    JoinDate = ((x.Element("JOIN_DATE") != null) ? (String.IsNullOrWhiteSpace(x.Element("JOIN_DATE").Value) ? DateTime.MaxValue : Convert.ToDateTime(x.Element("JOIN_DATE").Value)) : DateTime.MaxValue)

  }) 
  .GroupBy(x => x.CustomerId)
  .Select(x => x.First())
  .OrderBy(x => x.JoinDate)
  .ToList<Customer>();

如果值为 null 或为空或仅包含空白字符,则取而代之的是 DateTimeMaxValue。这应该将没有 JoinDateCustomers 放在该列表的末尾。如果您希望它们位于列表的开头,请使用 DateTime.MinValue.