1

I have an object like this:

public class MyObject{

  public int Prop1 {get;set;}
}

I'm doing a linq to sql query that returns a list of MyObject like this:

var TheQuery = from ....
               where ....
               select new MyObject()
               {

                 Prop1 = (...... ).Sum( d => d)

               }.ToList();

The problem is that Prop1 is a sum of a subquery and sometimes there might be nothing returned and the Sum is null, which can't be assigned to Prop1 because it's an int.

What's a good way around this.

Thanks for your suggestions.

1

2 Answers 2

1

how about using a range variable:

var TheQuery = from ....
               where ....
               let subquery = (...... )
               select new MyObject()
               {

                 Prop1 = subquery!=null ? (subquery.Sum( d => d) ?? 0) : 0;

               }.ToList();
Sign up to request clarification or add additional context in comments.

8 Comments

I could be wrong, but I think frenchie is saying that Sum returns null, not that the subquery he runs Sum on is null.
@juharr: according to msdn Sum() should always return a value, 0 for an empty collection.
Yes, the sum returns null; the sub query could still have elements in it
well then indeed this question is a duplicate, you should just use Prop1 = subquery.Sum( d => d) ?? 0 - what did you not like about the previous answer? Also this means you are not using the Standard Linq Sum method, what are you using?
@BrokenGlass but what if this is linq-to-sql it would translate into a SQL Sum that would return null if all the values in the sum are null.
|
1

I would simply promote your property to an int?. You have the sum of nothing, it's best to represent that as a null. The rationale is that it should be possible to have an actual sum that is 0. In this case, you do not have a sum of actual values, so keeping the null result allows you to preserve this difference.

Otherwise, you might consider (assuming the query returns the value as a nullable) invoking .GetValueOrDefault() on the result, which would normalize a null value to 0 in the case of a numeric type.

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.