【发布时间】:2017-06-22 13:11:12
【问题描述】:
我想根据包含 DateTime 的字符串类型属性对我的列表进行排序。为此,我将字符串属性转换为 OrderBy() 或 OrderByDescending() 内的 DateTime。所以这是我的代码:
var orderDirection = "ASC";
//AList already contains data.
AList = (orderDirection.Equals("ASC", StringComparison.OrdinalIgnoreCase))
? AList
.OrderBy(x => DateTime.ParseExact(x.LastUpdate, "g", WebCulture))
.ToList()
: AList
.OrderByDescending(x => DateTime.ParseExact(x.LastUpdate, "g", WebCulture))
.ToList();
不幸的是,只有当x.LastUpdate 包含有效的日期时间格式时,它才能正常工作。否则会报错。
因此,有什么方法可以让我们说用ParseExact() 中的有效日期时间字符串更改无效的日期时间字符串?或者有没有其他功能可以提供?
例如,“将字符串转换为日期时间,但对于无效字符串,将其替换为“1-1-1990 00:00:00.000”?
【问题讨论】:
-
例如,您可以使用
TryParseExact。甚至不将日期存储为字符串,而是立即将您的LastUpdate设为 DateTime 类型。 -
对于使用
TryParseExact,您能告诉我如何在OrderBy()中声明它吗?因为基本上,对于TryParseExact,它具有布尔值,不是吗? -
@Evk 不幸的是,属性类型必须是字符串。