我在我的数据库中有一个字段包含DateTime ?.我想对结果进行排序,这样的NULL在上面显示出来,然后通过日期时间递减,例如,Linq OrderByDescending,null first
null
null
2012-04-01
2012-01-01
2011-09-04
的原因是,我在看的到期日期,但有些项目不会过期。
我在我的数据库中有一个字段包含DateTime ?.我想对结果进行排序,这样的NULL在上面显示出来,然后通过日期时间递减,例如,Linq OrderByDescending,null first
null
null
2012-04-01
2012-01-01
2011-09-04
的原因是,我在看的到期日期,但有些项目不会过期。
您可以从排序表达式返回DateTime.MaxValue而不是null
,所以用null
日期的行会先被排序:
yourData.OrderByDescending(row => row.dateTimeField ?? DateTime.MaxValue);
伟大的解决方案。 –
你可以尝试这样的事:
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));
它比“可能是超高效”“显然是正确”,但它的至少一个起点。
您错过了任何订购条款。 –
我发现最简单的方法是:
data.OrderBy(Function(o) o.myDate IsNot Nothing).ThenByDescending(Function(o) o.myDate)
在C#
我认为...
data.OrderBy(o => o.myDate != null).ThenByDescending(o => o.myDate)
这也适用于LINQ to SQL。我不确定if(nullable, value)
是否会成功转换为SQL。
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)
我可以请您请您在答案中添加更多的上下文。仅有代码的答案很难理解。如果您可以在帖子中添加更多信息,它可以帮助提问者和未来的读者。 – RBT
我发现这是一个更好的解决方案,如果它不是一个日期时间的http:// stackoverflow.com/a/15247558/59508 – kiev