views:

36

answers:

2

I am trying to perform to calculation. I have a donations (d) table that contains Quantity Needed (d.QtyNeeded) and I need to determine the numbers of items still needed by pulling quantity filled (qtyfilled) from the donors table. Not every donation has a donor, so I need a conditional statement to handle nulls so the sum will work. When I try to compile, I am getting an error: *Operator '-' cannot be applied to operands of type 'int' and 'bool'. I am not great at Linq yet, what am I missing or is there a better way?

QtyOpen = d.QtyNeeded - (from dv in db.Donors
                                    select dv).All(v => v.QtyFilled == null)
                                    ? 0
                                    : (from dv in db.Donations
                                       select dv.QtyFilled).Sum()
A: 

The problem is not the LINQ statement, but rather precedence in the subtraction operator. Consider this example:

int result = quantity - true ? 0 : otherValue;

This fails to compile for the exact same reason, Operator '-' cannot be applied to operands of type 'int' and 'bool'. The solution is to simply group the conditional statement in parens:

int result = quantity - (true ? 0 : otherValue);

So, your example should compile by adding parens around your entire conditional operator statement.

wsanville
I tried this and it default to 0 even when the QtyFilled query returned 2. I may not have the implementation correct. Thanks. QtyOpen = d.QtyNeeded - (true ? 0 : (from dv in db.DonationVolunteerEntities where dv.DonationID == d.DonationID select dv).All(v => v.QtyFilled == null) ? 0 : (from dv in db.DonationVolunteerEntities select dv.QtyFilled).Sum()),
scottrakes
I saw what I was doing wrong. Your solution was perfect. Thanks.
scottrakes
A: 

Try filtering out the nulls within the initial select by adding a where in the select:

QtyOpen = d.QtyNeeded - (from dv in db.Donors 
                         where dv.QtyFilled != null
                         select dv.QtyFilled).Sum();
Jacob Proffitt