【问题标题】:LINQ and C# summaryLINQ 和 C# 总结
【发布时间】:2012-04-18 21:30:45
【问题描述】:

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

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

数据在数据表中。谁能帮我解决这个问题。

即:

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

(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 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 );

【问题讨论】:

  • 不-我只是为图像做了一些我有代码来生成数据表的图像
  • 3,2 的总成本是 255 为什么你说是 30?
  • @Saeed 因为它是成本 3 和他的 ParentId 2 的总和。所以 DataTable 中的 30 是 TotalCost。
  • 我在你的数据表中看不到这个,3的成本是1,2的成本是45,3的总成本是30,2的总成本是225,你怎么找到30作为2的总成本还有 3 个?

标签: c# linq datatable


【解决方案1】:

如果我理解正确,你需要一个递归例程,这不是我在纯 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);
}

【讨论】:

    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多