Inkey
Inkey

Reputation: 2207

Sum 2 Columns in Linq

I am trying to sum two columns that i have in LINQ. The following is my LINQ statement

var SigmaGood =  from n in db.tbl_dppITHr
                 where n.ProductionHour >= SelectedDateDayShiftStart
                 where n.ProductionHour <= SelectedDateEnd
                 select n.part1 + n.part2

ViewData["GoodTotal"] = SigmaGood.Sum();

I am trying to get a total for part1 + part2;

When i try and test the result i dont get any value back i get a blank.

Anyone any ideas what i am doing incorrect?

enter image description here

Upvotes: 5

Views: 2191

Answers (4)

Guvante
Guvante

Reputation: 19203

Are you certain you don't have a null in your input data? That may be rendered as a SQL SUM() which would go to null if any input value is null.

Upvotes: 0

weston
weston

Reputation: 54781

I would say blank must mean the key you're storing the value against doesn't match the key you are reading/displaying. If it did you would at least see 0, not blank.

Do it in two steps and debug it.

var total = sigmaGood.Sum();
ViewData["GoodTotal"] = total; //breakpoint on this line and check value of total.

Or hardcode a test value, I bet it still comes out blank:

ViewData["GoodTotal"] = 1234;

Upvotes: 1

mayabelle
mayabelle

Reputation: 10014

Try this:

var sum = db.tbl_dppITHr.Where(n => n.ProductionHour >= SelectedDateDayShiftStart
                                    && n.ProductionHour <= SelectedDateEnd)
                        .Sum(n => n.part1 + n.part2);

Upvotes: 0

Yosi Dahari
Yosi Dahari

Reputation: 6999

Are you sure part1 and part2 has value?

var SigmaGood =  from n in db.tbl_dppITHr
                 where n.ProductionHour >= SelectedDateDayShiftStart
                 where n.ProductionHour <= SelectedDateEnd
                 select n.part1 ?? 0 + n.part2 ?? 0

ViewData["GoodTotal"] = SigmaGood.Sum();

Upvotes: 0

Related Questions