[英]Linq OrderByDescending, null first
I have a field in my database that holds a DateTime?. 我的数据库中有一个包含DateTime的字段? I would like to sort the results so that the NULLs show up at the top, then descending by DateTime, eg, 我想对结果进行排序,以便NULL显示在顶部,然后按DateTime降序,例如,
null
null
2012-04-01
2012-01-01
2011-09-04
The reason is that I am looking at expiration dates, though some entries do not expire. 原因是我正在查看到期日期,但有些条目没有到期。
您可以从排序表达式返回DateTime.MaxValue而不是null
,因此首先排序具有null
日期的行:
yourData.OrderByDescending(row => row.dateTimeField ?? DateTime.MaxValue);
I find the most straightforward approach to be: 我发现最直接的方法是:
data.OrderBy(Function(o) o.myDate IsNot Nothing).ThenByDescending(Function(o) o.myDate)
in C# I think... 在C#我认为......
data.OrderBy(o => o.myDate != null).ThenByDescending(o => o.myDate)
This will also work with LINQ to SQL. 这也适用于LINQ to SQL。 I'm not sure if if(nullable, value)
will successfully translate to SQL. 我不确定if(nullable, value)
是否会成功转换为SQL。
You could try something like this: 你可以尝试这样的事情:
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));
It's more "obviously correct" than "likely to be super-efficient", but it's at least a starting point. 它比“可能超级高效”更“明显正确”,但它至少是一个起点。
Take a look at David Oesterreich's blog: 看看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.