我有以下Linq查询:
(from container in Container
join containerType in ContainerType on container.ContainerType equals containerType
where containerType.ContainerTypeID == someIDValue
select container).Max (row => Convert.ToInt64(row.SerialNumber))
只要至少有一个Container行符合条件,此查询就可以正常运行。如果没有符合条件的行,我会收到以下错误:
The null value cannot be assigned to a member with type System.Int64 which is a non-nullable value type
有没有办法可以重写这个,这样如果没有行满足查询,就会返回一个任意值,比如-1?
答案 0 :(得分:2)
您可以将查询的第一部分存储在列表中,然后在列表中执行Max。 类似于:
var query = (from container in Container
join containerType in ContainerType on container.ContainerType equals containerType
where containerType.ContainerTypeID == someIDValue
select container);
if(query != null)
int64 maxvalue = query.Max (row => Convert.ToInt64(row.SerialNumber))
(我在飞行中编码,请检查)
答案 1 :(得分:1)
如果没有结果,这将给你一个-1:
(
from container in Container
join containerType in ContainerType
on container.ContainerType equals containerType
where containerType.ContainerTypeID == someIDValue
select container.SerialNumber as long?
).DefaultIfEmpty().Max(sn => sn ?? -1)