有很多关于如何获取列中每个单元格总和的示例。我无法找到如何对一行中的每个单元格求和并将该总数添加到名为“Total”的新列中的示例。
C#DataTable有DataTable1.Compute("SUM(["Column Name"])", "")
我想在下面做什么的例子。但是,我还希望能够排除特定列,因为它们可能不包含数字。
修改该表是动态的,列数可能会发生变化。
答案 0 :(得分:5)
你可以使用这个循环:
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);
}
这适用于任何列类型。
答案 1 :(得分:3)
DataTable具有创建计算列的功能。在您的情况下,您可以将“总计”列创建为
DataTable1.Columns.Add("Total", typeof(Double));
DataTable1.Columns["Total"].Expression = "C1+C2+C3";
答案 2 :(得分:1)
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,甚至比较每行和每列的循环
答案 3 :(得分:0)
我会尝试这样的事情:
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
}
答案 4 :(得分:0)
试试这个。
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);
}
答案 5 :(得分:0)
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";
这是最简单的方法..!