我刚学习Linq并遇到了问题。对于某些验证,我从数据库中读取最后一个里程表,需要将其与下一个读数进行比较。里程表读数是传入数据的int,数据库是double(在dbml文件中更改为int)。
以下是我的代码:
private bool IsValidOdometer(string equipment, int odometerReading)
{
bool returnVariable = true;
CarteGraphDataDataContext db = new CarteGraphDataDataContext();
var odometer = (from p in db.EquipmentMainGenerals join q in db.EquipmentFuelLogs
on p.wdEquipmentMainGeneralOID equals q.wdEquipmentMainGeneralOID
where p.VehicleId == equipment
orderby q.Odometer descending
select q.Odometer).Take(1);
int previousOdometer = odometer;
if (odometer.Count() != 0)
{
if (odometerReading < previousOdometer)
{
returnVariable = false;
}
}
return returnVariable;
}
问题行是int previousOdometer = odometer;
。我得到的错误是:
无法将类型'System.Linq.IQueryable'隐式转换为'int'
我该如何解决这个问题?
答案 0 :(得分:4)
而不是Enumerable.Take
使用Enumerable.Single
。 Enumerable.Take
将返回IEnumerable
但Enumerable.Single
将返回单个实例(或抛出):
int odometer = (from p in db.EquipmentMainGenerals
join q in db.EquipmentFuelLogs
on p.wdEquipmentMainGeneralOID
equals q.wdEquipmentMainGeneralOID
where p.VehicleId == equipment
orderby q.Odometer descending
select q.Odometer).Single();
int previousOdometer = odometer;
另外,我会在这里明确键入odometer
,而不是像你那样隐式地输入。
最后你的行
CarteGraphDataDataContext db = new CarteGraphDataDataContext();
应该像using
这样阻止
using(CarteGraphDataDataContext db = new CarteGraphDataDataContext()) {
// okay to go
}