1

我有一个包含父子行的关系表。有些行有一个typeId,我想按类型获得总成本的摘要:

在此处输入图像描述

左边的列表是一些样本数据,右边的列表是预期的汇总结果。

数据在数据表中。谁能帮我这个。

IE:

  • typeId = 1:计算公式为:30(总成本 3,2)x 5(数量 2,1)x 3(数量 1,空)

(30 x 5 x 3) = 450

  • typeId = 2:计算公式为:12(总成本 5,1)x 3(数量 1,空)x 15(总成本 4,2)x 5(数量 2,1)x 3(数量 1,空值)

(12 x 3) + (15 x 5 x 3) = 261

这是一些示例代码

DataTable dt = new DataTable( "Summary" );

dt.Columns.Add( "Id", Type.GetType( "System.Int32" ) );
dt.Columns.Add( "ParentId", Type.GetType( "System.Int32" ) );
dt.Columns.Add( "Qty", Type.GetType( "System.Int32" ) );
dt.Columns.Add( "Cost", Type.GetType( "System.Decimal" ) );
dt.Columns.Add( "TotalCost", Type.GetType( "System.Decimal" ) );
dt.Columns.Add( "TypeId", Type.GetType( "System.Int32" ) );

dt.Rows.Clear();

DataRow row = dt.NewRow();
row["Id"] = 1;
row["ParentId"] = DBNull.Value;
row["Qty"] = 3;
row["Cost"] = 237.00;
row["TotalCost"] = 711.00;
row["TypeId"] = DBNull.Value;
dt.Rows.Add( row );

row = dt.NewRow();
row["Id"] = 2;
row["ParentId"] = 1;
row["Qty"] = 5;
row["Cost"] = 45.00;
row["TotalCost"] = 225.00;
row["TypeId"] = DBNull.Value;
dt.Rows.Add( row );

row = dt.NewRow();
row["Id"] = 3;
row["ParentId"] = 2;
row["Qty"] = 30;
row["Cost"] = 1.00;
row["TotalCost"] = 30.00;
row["TypeId"] = 1;
dt.Rows.Add( row );

row = dt.NewRow();
row["Id"] = 4;
row["ParentId"] = 2;
row["Qty"] = 1;
row["Cost"] = 15.00;
row["TotalCost"] = 15.00;
row["TypeId"] = 2;
dt.Rows.Add( row );

row = dt.NewRow();
row["Id"] = 5;
row["ParentId"] = 1;
row["Qty"] = 4;
row["Cost"] = 3.00;
row["TotalCost"] = 12.00;
row["TypeId"] = 2;
dt.Rows.Add( row );
4

1 回答 1

3

如果我理解正确,你需要一个递归例程,这不是我在纯 Linq 中尝试的,所以我会尝试这样的事情。

var summary =  
    (from r in dt.AsEnumerable()
    where r["TypeID"] != DBNull.Value  
    group r by (int) r["TypeId"] into results
    select new 
        { 
        results.Key , 
        TotalCost = results.Sum(r=> (decimal) r["TotalCost"] *  GetParentsQty(r) )
        }
    );


public int GetParentsQty(DataRow child )
{
    if (child["ParentID"] == DBNull.Value)
        return 1;

    var parent = (from row in dt.AsEnumerable() 
                  where (int) child["ParentID"] == (int) row["Id"] 
                  select row
                 ).Single();

    return (int) parent ["Qty"]  * GetParentsQty(parent);
}
于 2012-04-05T08:43:04.153 回答