Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Coalescence blues
Message
From
15/03/2017 04:47:57
Cetin Basoz
Engineerica Inc.
Izmir, Turkey
 
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 5.0
OS:
Windows 8.1
Network:
Windows Server 2012 R2
Database:
MS SQL Server
Application:
Desktop
Miscellaneous
Thread ID:
01649038
Message ID:
01649081
Views:
45
>>
>>        public static decimal ComputeWeightDifference(int transactionHeaders_Id,PICSEntities context)
>>        {
>>            decimal emWeight = (decimal) context.EMTransactions.Where(r => (r.TransactionHeaders_Id == transactionHeaders_Id)).Sum(r => r.Weight) ?? 0;
>>            decimal? detailsWeight = 0;
>>            emWeight = (decimal?) context.EMTransactions.Where(r => (r.TransactionHeaders_Id == transactionHeaders_Id)).Sum(r => r.Weight) ?? 0;
>>            detailsWeight = context.TransactionDetails.Where(r => (r.TransactionHeaders_Id == transactionHeaders_Id)).Sum(r => r.Weight);
>>            return (decimal)(emWeight  - (decimal) (detailsWeight ?? 0);
>>        }
>>
>>I'm really puzzled by this statement:
>>
>>          decimal emWeight = context.EMTransactions.Where(r => (r.TransactionHeaders_Id == transactionHeaders_Id)).Sum(r => r.Weight) ?? 0;
>>
>>
>>It won't compile. CS0019 Operator '??' cannot be applied to operands of type 'decimal' and 'int'
>>
>>But this does :
>>
>>
>>return emWeight  - (decimal) (detailsWeight ?? 0);
>>
>>
>>So is there a way to do is in one line, or do I first need to extract the transactions and check if there are none?
>
>
>If you want null results to be treated as 0 then you could just use : Sum(r=>r.Weight ?? 0)


Viv,
I think that is worse. If the weight itself is nullable (as this expression implies) then this would compile, but would error when there is no matching records.

And thanks for the heads up the correct way to write it, regardless the underlying field is nullable or not, is:
public static decimal ComputeWeightDifference(int transactionHeaders_Id, PICSEntities context)
{
	decimal emWeight = context.EMTransactions.Where(r => r.TransactionHeaders_Id == transactionHeaders_Id).Sum(r => (decimal?)r.Weight) ?? 0;
	decimal detailsWeight = context.TransactionDetails.Where(r => r.TransactionHeaders_Id == transactionHeaders_Id).Sum(r => (decimal?)r.Weight) ?? 0;
	return emWeight - detailsWeight;
}
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform