我遇到了一个同事的代码,并认为它可能效率低下
bool any = (from c in listDeviceMaxDate
where c.DeviceKey == m_deviceList[i].deviceKey
select c).Any();
if (!any)
{
latestDate = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
}
else
{
// from the list we have get the lastest max date from the flow table
DeviceDateTimeItem temp = (from c in listDeviceMaxDate
where c.DeviceKey == m_deviceList[i].deviceKey
select c).First();
latestDate = Convert.ToDateTime(temp.dateTimeMax);
}
我的第一直觉是存储 linq 查询,然后根据需要引用它,但后来我意识到First()
操作员可能会阻止 linq 实际获取不受约束的查询会执行的所有行。
我最初是如何考虑重构代码的:
var deviceList = from c in listDeviceMaxDate
where c.DeviceKey == m_deviceList[i].deviceKey
select c;
if (!deviceList.Any())
{
latestDate = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
}
else
{
// from the list we have get the lastest max date from the flow table
DeviceDateTimeItem temp = deviceList.First();
latestDate = Convert.ToDateTime(temp.dateTimeMax);
}
我的问题是First()
对第二个 linq 查询的调用是否会阻止它返回所有结果,因此,以原始方式执行它实际上是否更快?