有很多示例说明如何获取列中每个单元格的总和。例如,我无法找到如何对一行中的每个单元格求和并将该总数添加到名为“Total”的新列中的示例。
C# 数据表具有DataTable1.Compute("SUM(["Column Name"])", "")
我想在下面做的例子。但是,我也希望能够排除特定列,因为它们可能不包含数字。
编辑该表是动态的,列数可能会发生变化。
你可以使用这个循环:
table.Columns.Add("Total", typeof(decimal));
foreach (DataRow row in table.Rows)
{
decimal rowSum = 0;
foreach (DataColumn col in table.Columns)
{
if(!row.IsNull(col))
{
string stringValue = row[col].ToString();
decimal d;
if(decimal.TryParse(stringValue, out d))
rowSum += d;
}
}
row.SetField("Total", rowSum);
}
这应该适用于任何列类型。
DataTable 具有创建计算列的能力。在您的情况下,您可以将“总计”列创建为
DataTable1.Columns.Add("Total", typeof(Double));
DataTable1.Columns["Total"].Expression = "C1+C2+C3";
Yuriy 回答的示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
namespace DynamicColumns
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Total all quantity columns");
var dt = new DataTable ();
dt.Columns.Add ("ProductName", typeof(string));
dt.Columns.Add ("Qty1", typeof(int));
dt.Columns.Add ("Qty2", typeof(int));
dt.Columns.Add ("Qty3", typeof(int));
{
var dr = dt.NewRow ();
dr ["ProductName"] = "Keyboard";
dr ["Qty1"] = 2;
dr ["Qty2"] = 5;
dr ["Qty3"] = 6;
dt.Rows.Add (dr);
}
{
var dr = dt.NewRow ();
dr ["ProductName"] = "Mouse";
dr ["Qty1"] = 5;
dr ["Qty2"] = 1;
dr ["Qty3"] = 2;
dt.Rows.Add (dr);
}
string expression =
string.Join (" + ",
dt.Columns.OfType<DataColumn>()
.Where(x => x.DataType == typeof(int))
.Select(x => x.ColumnName)
.ToArray() );
dt.Columns.Add("Total", typeof(int)).Expression = expression;
Console.WriteLine ("Expression: {0}",expression);
Console.WriteLine ("\nProduct and totals");
foreach (var r in dt.Rows.OfType<DataRow>()) {
Console.WriteLine ("{0} {1}", r["ProductName"], r["Total"]);
}
}
}
}
输出:
Expression: Qty1 + Qty2 + Qty3
Product and totals
Keyboard 13
Mouse 8
我会冒险猜测这个(.Expression)是最高效的解决方案,与我们对每一行到每一列的 lambda-ing 相比,甚至与循环每一行和每一列相比
我会尝试这样的事情:
foreach (DataRow row in table.Rows) {
var rowSum = 0d;
foreach (DataColumn column in row.Table.Columns) {
//if row[column] is number
rowSum += Convert.ToDouble(row[column]));
//}
}
//at his point you have the the colums sum
}
尝试这个。
DataTable1.Columns.Add("Total", typeof(Double));
foreach (DataRow row in DataTable1.Rows)
{
int sum = row.Columns.Cast<DataColumn>().Sum(dc=>(int)row[dc]);
row.SetField("Total", sum);
}
DataTable1.Columns.Add("C1", typeof(Double));
DataTable1.Columns.Add("C2", typeof(Double));
DataTable1.Columns.Add("C3", typeof(Double));
DataTable1.Columns.Add("Total", typeof(Double));
DataTable1.Columns["Total"].Expression = "C1+C2+C3";
这是最简单的方法..!