【发布时间】:2018-11-07 04:04:34
【问题描述】:
我有一个 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 语句中。斗智斗勇就在附近。
【问题讨论】:
-
您不需要使用嵌套循环。只需要一个循环来检查元素是否乱序。对于每次迭代,您只需要跟踪先前迭代的元素。将之前迭代的元素与当前迭代的元素进行比较,检查它们是否乱序...
-
您为什么要尝试验证
orderby是否真的工作正常?另外,当l > 0时,您是否不希望所有j < l触发您的if? -
@NetMage 我正在尝试查看例如 SS(Shift Start) 的时间是否大于 SE(Shift End) 一天。如果这是真的返回假。
-
@elgonzo 如果我尝试不使用循环,我将如何评估它CompareDay[l].EventType == "SS"?
-
这个说法,和你在 cmets 里说的一样,是不是很明显是错误的?
(itCompareDay[l].EventDateTime.Value > itCompareDay[j].EventDateTime.Value)这会将当前 SS 与所有内容进行比较...您不想要一个仅包含 SE 值的子循环吗?