C# 使用LINQ为可为空的值施加排序规则

C# 使用LINQ为可为空的值施加排序规则,c#,.net,linq,C#,.net,Linq,我有一个与下面类似的对象列表(MyDataclass),我将使用LINQ查询仅获取那些满足SecondDate属性约束的对象,并最终根据所有属性对满足此约束的项进行排序 public class MyData { public Nullable<DateTime> FirstDate {get; set;} public DateTime SecondDate {get; set;} public TimeSpan SimpleInterval {get; s

我有一个与下面类似的对象列表(
MyData
class),我将使用LINQ查询仅获取那些满足
SecondDate
属性约束的对象,并最终根据所有属性对满足此约束的项进行排序

public class MyData
{
    public Nullable<DateTime> FirstDate {get; set;}
    public DateTime SecondDate {get; set;}
    public TimeSpan SimpleInterval {get; set;}
    public double SimpleValue {get; set;}
    ...
}
您可以使用:


您可以使用
HasValue
属性,例如:

orderby item.FirstDate.HasValue descending,
        item.FirstDate.GetValueOrDefault() descending
请注意,在查询表达式中使用多个
orderby
子句几乎肯定不是您想要做的事情-您的查询可能应该是:

var items = from item in list
            where ((now - item.SecondDate).TotalSeconds < threshold))
            orderby item.FirstDate.HasValue descending,
                    item.FirstDate.GetValueOrDefault() descending,
                    item.SecondDate descending,
                    item.SimpleInterval descending,
                    item.SimpleValue descending
            select item;

基本上,连续的
orderby
子句几乎总是一个错误。

在这种情况下,
HasValue
调用不是多余的吗,因为
default(DateTime)
等于
DateTime.MinValue
?@rich.okelly:no-首先,它将在所有空结果之前正确排序所有非空
DateTime.MinValue
结果。也许没有任何这样的非空结果-但我的代码在一般情况下满足要求。非常正确,在我删除它之前,我的原始答案中也有该检查,因为我确信它是不必要的。。。我的错!为什么连续的
orderby
子句可能是错误的?也许是因为上一个订单“覆盖”了上一个订单?@enzom83是的。同样的结果也可以通过颠倒
OrderBy
而不是使用
ThenBy
来实现。很可能,如果有人想要一个
,那么通过排序,他们会使用这种方法。
var items = from item in list
        where ((now - item.SecondDate).TotalSeconds < threshold))
        orderby item.FirstDate ?? DateTime.MinValue descending,
                item.SecondDate descending,
                item.SimpleInterval descending,
                item.SimpleValue descending
        select item;
orderby item.FirstDate.HasValue descending,
        item.FirstDate.GetValueOrDefault() descending
var items = from item in list
            where ((now - item.SecondDate).TotalSeconds < threshold))
            orderby item.FirstDate.HasValue descending,
                    item.FirstDate.GetValueOrDefault() descending,
                    item.SecondDate descending,
                    item.SimpleInterval descending,
                    item.SimpleValue descending
            select item;
var items = from item in list
            where ((now - item.SecondDate).TotalSeconds < threshold))
            orderby item.SimpleValue descending,
                    item.SimpleInterval descending,
                    item.SecondDate descending,
                    item.FirstDate.HasValue descending,
                    item.FirstDate.GetValueOrDefault() descending
            select item;