如何使用 Arraylist 的 orderby

本文关键字:orderby Arraylist 何使用 | 更新日期: 2023-09-27 18:33:21

我需要按降序(日期)获取数组列表的数据。为此,我们使用 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 子句,它会抛出错误。如果我使用,那么我无法获取具有空日期的数据。

如何使用 Arraylist 的 orderby

您可以使用三元运算符

OrderByDescending(x => x.Date!=null? DateTime.ParseExact(x.Date, @"dMyyyy", culture):DateTime.MinValue)

您只需要检查 null 并在 OrderByDescending lambda 表达式中返回一些默认日期(例如 '1970-01-01')。