0

我需要按降序(日期)获取数组列表的数据。为此,我们使用了 lambda 表达式的 orderby 特性。但是在这样做时,我面临一个问题。如果日期为空,则返回错误。错误是“输入字符串不是正确的日期时间”。

例子:

var comnData = ch.Request.NsType.SomeCollection.Cast<MiscType>().Select(x => x.Data).Where(x => !string.IsNullOrEmpty(x.Date)).OrderByDescending(x => DateTime.ParseExact(x.Date, @"dMyyyy", culture));

如果我不使用 where 子句,它会引发错误。如果我使用,那么我无法获取日期为空的数据。

4

2 回答 2

3

您可以使用三元运算符

OrderByDescending(x => x.Date!=null? DateTime.ParseExact(x.Date, @"dMyyyy", culture):DateTime.MinValue)
于 2013-10-01T05:34:20.170 回答
1

您只需要在 OrderByDescending lambda 表达式中检查 null 并在这种情况下返回一些默认日期(如“1970-01-01”)。

于 2013-10-01T05:27:27.523 回答