我希望将不同值的总和与DataTable中的另一列分组

时间:2016-09-03 09:29:45

标签: c# asp.net

static void Main(string[] args){
     DataTable dt = new DataTable("Product");
     dt.Columns.Add("ProductID", typeof(Int32));         
     dt.Columns.Add("ProductName");
     dt.Columns.Add("SPAREIECODE");
     dt.Columns.Add("SP_COSTPRICE", typeof(Double));
     dt.Columns.Add("QTY", typeof(Int32));
     dt.Rows.Add(1, "Pen", "P_12", 14.50, 1);
     dt.Rows.Add(1, "Pen", "P_8", 14.50, 1);
     dt.Rows.Add(1, "Pen", "P_7", 50.35, 2);
     dt.Rows.Add(2, "InkPot", "iP_2", 30.80, 1);
     dt.Rows.Add(2, "InkPot", "iP_1", 30.80, 1);
     dt.Rows.Add(2, "InkPot", "iP_4", 30.80, 1);
     dt.Rows.Add(3, "PencilBox", "Pb_4", 80.05, 1);
     dt.Rows.Add(3, "PencilBox", "Pb_2", 80.05, 1);
     dt.Rows.Add(4, "Compass", "cP_8", 102.36, 1);
     var result = from r in dt.AsEnumerable()group r by 
                  new { Id = r["ProductID"], name = r["ProductName"] } 
                  into gselect new {
                            Id = g.Key.Id,
                            pName = g.Key.name, 
                            sum = g.Sum(r => r.Field<Double> ("SP_COSTPRICE"))
                            };
     foreach (var r in result){
          Console.WriteLine("Id {0}, name {1}, Sum {2}", r.Id, r.pName, r.sum);
          Console.ReadLine();}
 }

// -----输出是Id = 1 Pname = Pen Sum = 79.35 - 但我需要显示所有不同的ID

0 个答案:

没有答案