Giraffe Giraffe -4 years ago 109
C# Question

datatable.compute with multiple filters

I want to sum the value of a certain column on my data table, where column x is equal to a value AND column y is equal to another value. I can implement this when I just filter on column X as follows:

dt.Compute("Sum([Cost])", "[COLUMNX] = 'blah'");


This works fine, however I now want to add another column to the filter, so something like
dt.Compute("Sum([Cost])", "[COLUMNX] = 'blah'", "[COLUMNY] = 'blah'");


How can I filter on two different columns please.

Answer Source

You can use AND as explained here

dt.Compute("Sum([Cost])", "[COLUMNX] = 'blah' AND [COLUMNY] = 'blah'");  

or with LInq-To-DataTable which has no limits:

double sumCost = dt.AsEnumerable()
    .Where(r => r.Field<string>("COLUMNX")=="blah" && r.Field<string>("COLUMNY")=="blah")
    .Sum(r => r.Field<double>("Cost"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download