我的数据库中有一个字段包含日期时间?.我想对结果进行排序,使 NULL 显示在顶部,然后按 DateTime 降序,例如,
null null 2012-04-01 2012-01-01 2011-09-04
原因是,我正在寻找过期日期,虽然有些条目没有过期。
你可以试试这样:
var nulls = table.Where(x => x.NullableDateTimeField == null); var notNulls = table.Where(x => x.NullableDateTimeField != null); var result = nulls.Concat(notNulls.OrderByDescending(x => x.NullableDateTimeField));
它更多的是“明显正确”而不是“可能超级有效”,但它至少是一个起点。
可以从排序表达式返回 日期时间,最大值而不是 null,因此带有 null日期的行首先排序:
null
yourData.OrderByDescending(row => row.dateTimeField ?? DateTime.MaxValue);
我发现最直接的方法是:
data.OrderBy(Function(o) o.myDate IsNot Nothing).ThenByDescending(Function(o) o.myDate)
我想..。
data.OrderBy(o => o.myDate != null).ThenByDescending(o => o.myDate)
这也适用于 LINQtoSQL。我不确定 if(nullable, value)是否能成功转换成 SQL。
if(nullable, value)
看看 David Oesterreich 的博客:
var queryResult = orderedProducts from enumerableProducts order by orderedProducts.ProductName, orderedProducts.Price != null ? 1 : 0 descending, orderedProducts.Price select orderedProducts;
与上面的版本类似,但是使用了 c # v6的语法
tickets.OrderByDescending(x => x?.Erstellt ?? DateTime.Now)