【问题标题】:OrderBy date format with null values具有空值的 OrderBy 日期格式
【发布时间】:2020-11-04 15:47:19
【问题描述】:

我有以下格式的xml

<Root>
   <dates>
      <start>20201101</start>
      <end>20201103</end>
   </dates>
   <dates>
      <start>20201101</start>
      <end />
   </dates>
   <dates>
      <start>20201105</start>
      <end>20201108</end>
   </dates>
</Root>

我想用两个 order by 条件对节点进行排序。首先按start 排序,然后按end 使用日期格式。如果end 节点值为空,那么我需要将其保留在订单的顶部。因此,对于上面的示例 XML,顺序如下(1st 和 2nd 的开始日期相同,但 2nd 的日期为空,因此将首先考虑)

   <dates>
      <start>20201101</start>
      <end />
   </dates>
   <dates>
      <start>20201101</start>
      <end>20201103</end>
   </dates>
   <dates>
      <start>20201105</start>
      <end>20201108</end>
   </dates>
string xmldoc = "<Root><dates><start>20201101</start><end>20201103</end></dates><dates><start>20201101</start><end></end></dates><dates><start>20201105</start><end>20201108</end></dates></Root>";
            inputDoc.LoadXml(xmldoc);

    XElement e = XElement.Load(new XmlNodeReader(inputDoc));
    var dates = (from res in e.Descendants("dates") select res);
    var newDate = (from ele in dates   
                         orderby DateTime.ParseExact(ele.Element("start").Value, "yyyyMMdd", CultureInfo.InvariantCulture) ascending, DateTime.ParseExact(ele.Element("end").Value, "yyyyMMdd", CultureInfo.InvariantCulture) descending
                         select ele);

使用上面的代码,我无法处理 end 日期的空值。我认为一种选择是在初始 xml 中使用 DateTime.MaxValue 更新end,当它为空时,然后应用订单逻辑。那么实现这一目标的最佳方法是什么。

【问题讨论】:

    标签: c# linq date


    【解决方案1】:

    只需在订购条件本身中将空的“end”元素替换为DateTime.MaxValue

    from ele in dates   
        orderby DateTime.ParseExact(ele.Element("start").Value, "yyyyMMdd", CultureInfo.InvariantCulture) ascending,
        String.IsNullOrWhiteSpace(ele.Element("end").Value) ? DateTime.MaxValue : DateTime.ParseExact(ele.Element("end").Value, "yyyyMMdd", CultureInfo.InvariantCulture) descending
        select ele;
    

    【讨论】:

      猜你喜欢
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 2013-06-17
      • 2019-09-14
      • 1970-01-01
      相关资源
      最近更新 更多