Kuntady Nithesh
Kuntady Nithesh

Reputation: 11721

C#, Finding 2 columns sum together in linq

I am bit new to linq .

How do I get the total sum of two columns in my data table.

Let say 2 columns are A& B . I want numeric sum of entire column A and entire column B (i.e totalSum= sum(A)+sum(B))

IMP : If I have any field in either of 2 columns a non numeric field (eg AB,WH,DBNULL) . That field should be considered as zero while summing up the values so that it wont throw any exception.

Upvotes: 0

Views: 1428

Answers (1)

aL3891
aL3891

Reputation: 6275

For each row or the sum of entire column A and entire column B?

In the first case you could do a select:

var resultWithSum = from row in table
select new{ 
  A = row.A, //optional
  B = row.B, //optional
  sum = row.A + row.B
}

Otherwise you can do:

  result = table.Sum(row => row.A + row.B)

Upvotes: 4

Related Questions