Sum method in LINQ with long type

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.

Tags:

C#

Linq