Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum method in LINQ with long type

Tags:

c#

linq

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...

like image 489
Kourosh Avatar asked Nov 07 '13 23:11

Kourosh


2 Answers

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.

like image 78
D Stanley Avatar answered Sep 21 '22 15:09

D Stanley


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.

like image 38
evanmcdonnal Avatar answered Sep 20 '22 15:09

evanmcdonnal