2010-06-30 82 views
0

我有以下的Linq查询:LINQ查询帮助 - 检测NULL值

(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)) 

该查询的伟大工程的,只要至少一个集装箱排符合标准。如果没有行符合条件的,我得到以下错误:

The null value cannot be assigned to a member with type System.Int64 which is a non-nullable value type 

有没有办法让我能改写这一点,如果没有行满足任意值被返回的查询,说-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) 
2

您可以将第一部分查询存储在列表中,然后在列表中执行最大值。 类似的东西来:

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)) 

(我编码它的飞行,请检查它)

+0

你可能有在第一个查询的末尾添加一个.SingleOrDefault(),如下所示:select container).SingleOrDefault(); – Tahbaza 2010-06-30 16:06:39

+0

查询不会为空,它将是空的。 – Toby 2010-06-30 16:09:55

+0

托比你是对的。对不起,大家 – frabiacca 2010-06-30 16:11:50