I like to write synthetic query on db tables like the following:
Decimal sum = MyDataContext.MyTable.Where(el => el.Client == selectedClien).Sum(el => el.Value.GetValueOrDefault(0));
Unfortunately it throws an error if the where clause return no elements at all.
Before using .Sum I should check with .Any if I have some elements but the resulting code is ugly compared with the initial one. Don’t think putting a try/catch block is a good solution.
Do you have something better that the following code to suggest ?
if (MyDataContext.MyTable.Where(el => el.Client == selectedClien).Any())
sum = MyDataContext.MyTable.Where(el => el.Client == selectedClien).Sum(el => el.Value.GetValueOrDefault(0));
else sum = 0;
Thanks
Filippo
Added after some more investigation:
MyDataContext.MyTable.Where(el => el.Client == selectedClien).Sum(el => el.Value).GetValueOrDefault(0)
The code above works well when the collection is empty. The reason I put ‘GetValueOrDefault(0)’ in the lambda inside .Sum() is the field ‘Value’ is Decimal?, so it could be null. I have not yet tested the case where some elements have null values.
Surprisingly (to me) i introduced a possible exception cause trying to make my code more robust!
The right way to write robust code is the following:
As stated in a comment above and in the msdn documentation the
is robust against null values and empty collections. GetValueOrDefault() assures it returns a non null Decimal.
Anyway it is still not very clear why the initial code throws exception.