0

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 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

you might have to add a .SingleOrDefault() on the end of the first query, like so: select container).SingleOrDefault();
query wouldn't be null, it would be empty.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.