繁体   English   中英

Linq OrderByDescending,首先为null

[英]Linq OrderByDescending, null first

我的数据库中有一个包含DateTime的字段? 我想对结果进行排序,以便NULL显示在顶部,然后按DateTime降序,例如,

null
null
2012-04-01
2012-01-01
2011-09-04

原因是我正在查看到期日期,但有些条目没有到期。

您可以从排序表达式返回DateTime.MaxValue而不是null ,因此首先排序具有null日期的行:

yourData.OrderByDescending(row => row.dateTimeField ?? DateTime.MaxValue);

我发现最直接的方法是:

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 nulls = table.Where(x => x.NullableDateTimeField == null);
var notNulls = table.Where(x => x.NullableDateTimeField != null);

var result = nulls.Concat(notNulls.OrderByDescending(x => x.NullableDateTimeField));

它比“可能超级高效”更“明显正确”,但它至少是一个起点。

看看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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM