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 ?
var sum = dt.AsEnumerable()
            .Where(r => r.Field<int>(2)==value)
            .Sum(r =>  r.Field<int>(3));
                        var sum = dt.AsEnumerable().Where(dra => ???).Sum(dra => dra.Field<int>(3));
                        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;
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With