Search code examples
c#linqc#-4.0datatable.select

DataTable need to sum a column with filter on it


I have a data table in C# with columns:

Product|Status|ShipedVolume|TotalVolume

A     New        0           10     
A     New        5           20
B     Closed     7           20

I want to sum (TotalVolume-ShipedVolume) filtered by product and Status.

For example I want to query how many not shipped item I have for product A, in this example the answer is 25. The same question for product B will be 0.

How can I code it?


Solution

  • Try this, assuming your number columns type is int:

    var query = (from t in table.AsEnumerable()
                 where t["Status"].ToString().Trim() != "Closed" 
                      && t["Product"].ToString().Trim() == "B"
                 select Convert.ToInt32(t["TotalVolume"]) 
                     - Convert.ToInt32(t["ShipedVolume"])).Sum();