DataTable需要对带有过滤器的列求和

时间:2013-12-26 13:44:18

标签: c# linq c#-4.0 datatable.select

我在C#中有一个带有列的数据表:

  

产品|状态| ShipedVolume | TotalVolume

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

我想按产品和状态过滤总和(TotalVolume-ShipedVolume)。

例如,我想查询产品A中有多少未装运的商品,在此示例中答案为25。 产品B的相同问题是0。

我该如何编码?

3 个答案:

答案 0 :(得分:2)

MSDN的使用示例:

DataTable table;
table = dataSet.Tables["YourTableName"];

// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount) order by name", "");

在总金额标签中显示结果,如下所示:

lblTotalAmount.Text = sumObject.ToString();

答案 1 :(得分:2)

尝试此操作,假设您的数字列类型为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();

答案 2 :(得分:1)

这很有效。请注意,您无法直接在差异上创建SUM表达式 - 请参阅下面的注释:

//fill table from data source ... not shown.

//setup desired filter criteria
string strExpr = "Product = 'B' AND Status= 'New'";
//Add a new column to the table to perform hold the difference of each row
//You have to do this since the sum expreession can't use more than 1 column
//See: Remarks section of: http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx
myTable.Columns.Add("Diff", typeof(Int32), "TotalVolume - ShipedVolume");
Object sumDiffColumn = myTable.Compute("sum(Diff)",strExpr);

Int32 result=-1;
//check to see if the filter returned empty rows or not before cast is performed
if (sumDiffColumn is DBNull)
{
    result = 0;
}
else
{
    result = Convert.ToInt32(sumDiffColumn);
}

MessageBox.Show("Sum of Difference:"+result.ToString()+ " for filter:"+strExpr);