Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ sum datatable column where

Tags:

c#

linq

I've a LINQ syntax where I'm getting the sum of a column, but I want to get the sum of a column where another column contains a particular value.

Here is my syntax :

var sum = dt.AsEnumerable().Sum(dra => dra.Field<int>(3));

Here, dt is the datatable, 3 is the column index. Datatable data could be :

a     b     c      d
1     4     6      7
2     0     7      5
2     7     8      6
3     6     9      3
3     5     1      6

The datatable column index would be 2 for where condition.

How can I apply WHERE condition ?

like image 781
Harshit Avatar asked Apr 21 '15 03:04

Harshit


3 Answers

var sum = dt.AsEnumerable()
            .Where(r => r.Field<int>(2)==value)
            .Sum(r =>  r.Field<int>(3));
like image 115
Carbine Avatar answered Oct 06 '22 01:10

Carbine


var sum = dt.AsEnumerable().Where(dra => ???).Sum(dra => dra.Field<int>(3));
like image 21
Tim Destan Avatar answered Oct 06 '22 00:10

Tim Destan


private long getSumFiled(DataTable dt, string sumFiled, string whereField,int intStatus)
    {
        long sum = dt.AsEnumerable()
                    .Where(r => r.Field<int>(whereField) == intStatus)
                    .Sum(x => x.Field<Int64>(sumFiled));
        return sum;
    }
like image 21
Ata Hoseini Avatar answered Oct 06 '22 00:10

Ata Hoseini