tags:

views:

32

answers:

2

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 System.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?

+2  A: 

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)

frabiacca
you might have to add a .SingleOrDefault() on the end of the first query, like so: select container).SingleOrDefault();
Tahbaza
query wouldn't be `null`, it would be empty.
Toby
toby you're right. sorry to everyone
frabiacca
+1  A: 

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