Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Coalescence blues
Message
De
15/03/2017 09:13:01
Cetin Basoz
Engineerica Inc.
Izmir, Turquie
 
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Versions des environnements
Environment:
C# 5.0
OS:
Windows 8.1
Network:
Windows Server 2012 R2
Database:
MS SQL Server
Application:
Desktop
Divers
Thread ID:
01649038
Message ID:
01649088
Vues:
28
>
>           decimal emWeight = context.EMTransactions.Where(r => r.TransactionHeaders_Id == transactionHeaders_Id).Sum(r => (decimal?)r.Weight) ?? 0;
>            // decimal? emWeight = 0;
>            // var q = context.EMTransactions.Where(r => (r.TransactionHeaders_Id == transactionHeaders_Id));
>            // if ((q.Count() == 0) == false)
>            // {
>            //    emWeight = q.Sum(r => r.Weight);
>            // }
>            decimal detailsWeight = context.TransactionDetails.Where(r => (r.TransactionHeaders_Id == transactionHeaders_Id)).Sum(r => r.Weight);
>            return emWeight    - detailsWeight;
>
>
>This indeed works. If I'm right
Sum(r => (decimal?)r.Weight)
the (decimal?) type definition applies to Sum() because Weight is defined a non nullable in my SQL table.
>
>Many thanks for your help.

Marc,
If you check my reply to Viv (I think I CCed to you?), the most secure way is:
           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;
This way you do not have to think of if the underlying field r.Weight is nullable or not. Otherwise it would not only depend on underlying field is nullable or not but if there are matching records to sum as well.

Edit: BTW (decimal?) would also apply to a decimal. i.e.:

decimal t = (decimal?)0??0;
decimal t = (decimal?)null??0;

in either case t is decimal 0.



PS: I removed the parentheses just because they were not needed.
Ç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
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform