How can I get sum of some items in long type... here is mycode :
using (gEn myEntities = new gEn)
{
var load = (from items in myEntities.Orders
select items.PayO).DefaultIfEmpty(0).Sum();
}
but the Sum gives me int... I also wants to know if DefaultIfEmpty method has any conflict with Sum method when use it for long type... thanks in advance...
Sum
returns whatever type the expression used in the select
returns (provided it's one of the defined overloads). If you want to return a long then cast items.PasO
:
var load = (from items in myEntities.Orders
select (long)(items.PayO)
)
.DefaultIfEmpty(0).Sum();
I also wants to know if DefaultIfEmpty method has any conflict with Sum method when use it for long type
No, DefaultIfEmpty
works with any type, including long
. As long as there's a Sum
overload for that type it works just fine.
If Sum()
returns an int
it's because that's the data type of your collection. All these LINQ to Object methods are generic. And no, DefaultIfEmpty
will have no side effects. It's just going to give you 0 if there are no items in the collection, then Sum
is going to work on the result of that which is going to be an IEnumberable<int>
with a single item which will have a value of 0.
I'm just assuming you're using EF here. If that is the case you need to either do a cast after you retrieve the data or change your model on the C# side so that it has long
. You may also want to check what the data type for that table is because if you generated your C# model from the data source and it's using an int32, then that's probably what your table has too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With