Linq to EF:查找从现在开始的最接近的可为空日期时间



我尝试过,但仍然对可空日期时间的计算和相应的linq语法感到困惑。我正在使用 Linq to EF 来查找其 StartTime(可为空)最接近现在的最近任务。为简化起见,请参阅演示:

static void Main(string[] args)
{
    DateTime? d0 = null;
    DateTime? d1 = new DateTime(2013, 1, 1);
    DateTime? d2 = new DateTime(2014, 1, 1);
    DateTime? d3 = new DateTime(2015, 1, 1);
    DateTime? d4 = null;
    List<DateTime?> dts = new List<DateTime?>() { d0, d1, d2, d3, d4 };
    var v = dts.OrderBy(x => (DateTime.Now - (x)));//runs, but I need Math.Abs, and the nulls are before in order, I want nulls be behind
    //var v = dts.OrderBy(x => (Math.Abs((DateTime.Now - (x)))));//best overloaded: Math.Abs(sbyte)
    //var v = dts.OrderBy(x => (DateTime.Now - (x)).Milliseconds);//TimeSpan? does not contain 'Milliseconds'
    foreach (var x in v)
        Console.WriteLine(x);
    Console.ReadLine();
}

我正在使用.net 4.0,谢谢!

我最终用x.Value替换了x,编译错误消失了。

    static void Main(string[] args)
    {
        DateTime? d0 = null;
        DateTime? d1 = new DateTime(2013, 1, 1);
        DateTime? d2 = new DateTime(2014, 1, 1);
        DateTime? d3 = new DateTime(2015, 1, 1);
        DateTime? d4 = null;
        List<DateTime?> dts = new List<DateTime?>() { d0, d1, d2, d3, d4 };
        //I finally replaced x with x.Value, and compile error disappeared
        var v = dts.Where(x => x.HasValue).OrderBy(x =>
            (Math.Abs((DateTime.Now - x.Value).TotalMilliseconds)));
        foreach (var x in v)
            Console.WriteLine(x);
        Console.ReadLine();
    }

这有效

var Nearest = dts.Where( d => d != null 
                              && 
                              ( (DateTime.Now - d) > new TimeSpan(0, 0, 0, 0, 0) 
                                 || 
                                ((TimeSpan)(DateTime.Now - d)).Negate() > new TimeSpan(0, 0, 0, 0, 0)
                              )
                       ).OrderBy(d => d.Value).First();

它打印最接近日期时间的值。现在

相关内容

  • 没有找到相关文章

最新更新