LINQ和C#汇总

时间:2012-04-05 06:20:57

标签: c# linq datatable

我有一个具有父子行的关系表。有些行有typeId,我希望按类型获得总费用的摘要:

enter image description here

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

数据位于数据表中。任何人都可以帮助我。

即:

  • typeId = 1:计算方法如下: 30(总费用3,2)x 5(数量为2,1)x 3(数量为1,空) < / LI>

(30 x 5 x 3)= 450

  • typeId = 2:计算方法如下: 12(总费用5,1)x 3(数量为1,null) x 15(总费用4,2)x 5(数量为2,1)x 3(数量为1,无效)

(12×3)+(15×5×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 );

1 个答案:

答案 0 :(得分: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);
}