开发者

Linq Query Help - Detecting Null Values

I have the following Linq query:

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

This query works great as long as at least one Container row meets the criteria. If no rows meet the criteria, I get the following error:

The null value cannot be assigned to a member with type Sy开发者_运维百科stem.Int64 which is a non-nullable value type

Is there a way I can rewrite this so that if no rows satisfy the query an arbitrary value gets returned, say a -1?


you can store first part of your query in a list and then do the Max on the list. Something similar to:

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

(i coded it on the fly, pls check it)


This will give you a -1 if there are no results:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜