2

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

产品|状态|装运量|总体积

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

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

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

我该如何编码?

4

3 回答 3

3

试试这个,假设你的数字列类型是 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();
于 2013-12-26T14:12:45.227 回答
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();
于 2013-12-26T13:51:55.087 回答
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);
于 2013-12-26T15:05:46.383 回答