Linq日期比较

时间:2015-05-06 08:27:46

标签: c# linq

我的查询就像

var TMJM = (from TT in r2ge.Transcription_Tracker
            join TMA in r2ge.Transcription_Master on TT.Transcription_Id equals TMA.Transcription_Id
            select new
            {
                Trans_Id = TMA.Transcription_Id,
                Modified_dtm = TMA.Modified_dtm
            }).Distinct();

var qq = TMJM.Where(dr => (dr.Modified_dtm.Date >= sev_back_datetime) && (dr.Modified_dtm.Date <= DateTime.Now.Date));

当数据存在时,它会提供输出Enumeration yielded no results 但是当我将开始日期和结束日期分开时,它会显示日期,但是当我将开始日期和结束日期结合起来时,它将不会给出输出.. 查询中有任何错误吗?

1 个答案:

答案 0 :(得分:1)

评估日期的每个部分可能充满问题。我假设你这样做是为了删除有时会出现问题的时间部分。随后,您只需评估日期时间变量的“日期”部分。这个小例子应该解释一下。

class Program
{
    static void Main(string[] args)
    {

        List<DateTime> dates = new List<DateTime>();

        dates.Add(DateTime.Now.AddDays(-50));
        dates.Add(DateTime.Now.AddDays(-51));
        dates.Add(DateTime.Now.AddDays(-52));
        dates.Add(DateTime.Now.AddDays(-53));
        dates.Add(DateTime.Now.AddDays(-99));
        dates.Add(DateTime.Now.AddDays(-100));
        dates.Add(DateTime.Now.AddDays(-101));

        var sev_back_datetime = DateTime.Now.AddDays(-100);

        Console.WriteLine(sev_back_datetime.Date.ToShortDateString());
        Console.WriteLine("---------------------");

        var query = from date in dates 
                    where date.Date >= sev_back_datetime.Date && 
                          date.Date <= DateTime.Now.Date 
                    select date;

        foreach (var date in query.ToList())
            Console.WriteLine(date.ToShortDateString());

        Console.ReadLine();
    }


}

编辑 - 您的直接示例。

        var TMJM = (from TT in r2ge.Transcription_Tracker
                    join TMA in r2ge.Transcription_Master on TT.Transcription_Id equals TMA.Transcription_Id
                    select new
                    {
                        Trans_Id = TMA.Transcription_Id,
                        Modified_dtm = TMA.Modified_dtm
                    }).Distinct();


        var qq = TMJM.Where(dr => (EntityFunctions.TruncateTime(dr.Modified_dtm) >= EntityFunctions.TruncateTime(sev_back_datetime)) && (EntityFunctions.TruncateTime(dr.Modified_dtm) <= EntityFunctions.TruncateTime(DateTime.Now)));