如果LINQ查询返回的条件已多次检查

时间:2018-11-06 17:34:48

标签: c# linq

我有一个LINQ查询,用于查看按日期和时间返回时事件是否乱序。

            var itCompareDay = (from h in db.DailyGPSTables
                                where h.EmplID == EmpID
                                     && (DbFunctions.TruncateTime(h.EventDateTime) >= startDate.Date)
                                     && (DbFunctions.TruncateTime(h.EventDateTime) <= endDate.Date)
                                     && (h.EventType == "SS" || h.EventType == "JS" || h.EventType == "LS" || h.EventType == "LE" || h.EventType == "JE" || h.EventType == "SE")
                                orderby h.EventDateTime
                                select h).ToList();

然后我检查每个项目,以确保其当天的顺序正确。

       for (int l = 0; l <= itCompareDay.Count - 1; l++)
        {
       if (itCompareDay[l].EventType == "SS" && (itCompareDay[l].EventDateTime.Value.ToShortDateString()==startDate.Date.ToShortDateString()))
       {
       Response.Write("<br>"+ l +"   " + itCompareDay[l].EventType +" is'SS' and dates match" + itCompareDay[l].EventDateTime.Value.ToShortDateString() +"=" + startDate.Date.ToShortDateString() + "<br>");
       for (int j = 0; j <= itCompareDay.Count - 1; j++)
        {
        //Response.Write("<br>: If this " + itCompareDay[l].EventType + itCompareDay[l].EventDateTime.Value + " is greater than " + itCompareDay[j].EventType + itCompareDay[j].EventDateTime.Value);
        if (itCompareDay[l].EventDateTime.Value > itCompareDay[j].EventDateTime.Value)
        {
           Session["EOOmessage"] = "On " + itCompareDay[l].EventDateTime.Value.Date.ToShortDateString() + " " + itCompareDay[l].EventType + " is After " + itCompareDay[j].EventType;
           Session["rowNumber"] = rowNumber;
           return false;
        }
      }
   }
}

虽然这似乎可行,但它会影响性能,因为它会检查主查询中返回的每个项目的if语句。我要检查200个条件。

我尝试了一个for循环和一个foreach循环以及许多其他混合方法,它们返回了相同的结果。我尝试了删除toList()并将linq查询也添加到if语句中。终点就在附近。

1 个答案:

答案 0 :(得分:0)

通过剔除将要比较的内容来删除大部分操作。另外,要比较日期,请使用Date属性而不是字符串compare

最后使用linq方法Any,如果任何一项/ 第一项符合条件,则返回true。

var comparedToDates = itCompareDay.Where(dy => dy.EventType == "SE")
                                  .Where(dy => dy.Date >= startDate.Date)
                                  .ToList();
return
   itCompareDay.Where(dy => dy.EventType == "SS")
               .Where(dy => dy.Date == startDate.Date); // Compare this way instead 
               .Any(SS => comparedToDates.Any( SE => SS > SE )); // Let it 
                                                                 // work the compare