Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract columns in a table with LINQ

I need to subtract one column from another column in a table in my database by using LINQ

Table trial

Userid  Money     Type

x       500       +

y       250       +

x       300       -

y       100       -

x       120       -

I need to do this;

500 - 300 - 120 for x

and

250 - 100 for y.

how do i do that?

I tried grouping like trial.userid and trial.money, trial.type. Basically, I think i have to group the users via id's and i need to add the + and subtract - from the sum of the addition please aid me.

like image 267
Bastardo Avatar asked Dec 28 '22 00:12

Bastardo


2 Answers

How about something like:

var query = from row in db.Rows
            group row by row.UserId into tmp
            select new {
              UserId = tmp.Key,
              Money = tmp.Sum(x => x.Type == '+' ? x.Money : -x.Money)
            };
like image 198
Marc Gravell Avatar answered Jan 09 '23 07:01

Marc Gravell


Try something like this for each group:

group.Sum(row => row.Type == "+" ? row.Money : -row.Money)
like image 39
Mark Byers Avatar answered Jan 09 '23 06:01

Mark Byers