在数据表中总结
Summing up in Datatable
我有一个类似
的数据表
Full Name ID 7/13/2015 7/14/2014
A 1 20 30
A 2 30 50
B 3 50 70
B 4 60 30
C 5 20 30
C 6 30 80
C 7 10 30
我想在此数据表中再添加一行,其中包含特定日期每个人的总和
Full Name ID 7/13/2015 7/14/2014
A 1 20 30
A 2 30 50
A total 50 80
B 3 50 70
B 4 60 30
C 5 20 30
C 6 30 80
C 7 10 30
我知道如何创建新行并添加名称和 ID,但我可以使用 c# 模块来计算特定总和。我抬头一看,他们是 table_name.Compute();但我在实施时遇到错误。
- 请注意,列全名的值带有 space,并且该列中的值也可以包含 space。
这是一个 return 新的 object[]
函数,它将给定 table 中的每一行与给定列索引中的指定值进行匹配。匹配的行在所有其他列上求和,总和在相应的索引中 returned。
private object[] GetSumRow(DataTable table, string nameToMatchAgainst, int nameColumnIndex = 0)
{
object[] sumRow = new object[table.Columns.Count];
IEnumerable<DataRow> rows = table.Rows.Cast<DataRow>().Where(r => r[nameColumnIndex].ToString() == nameToMatchAgainst);
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == nameColumnIndex)
{
sumRow[i] = nameToMatchAgainst;
}
else
{
sumRow[i] = rows.Sum(r => int.Parse(r[i].ToString()));
}
}
return sumRow;
}
因此调用 var sumRow = GetSumRow(yourExampleTable, "A")
会 return ["A", 3, 50, 80]
,然后您可以使用 yourExampleTable.Rows.Add(sumRow)
.
添加到 table
我有一个类似
的数据表Full Name ID 7/13/2015 7/14/2014
A 1 20 30
A 2 30 50
B 3 50 70
B 4 60 30
C 5 20 30
C 6 30 80
C 7 10 30
我想在此数据表中再添加一行,其中包含特定日期每个人的总和
Full Name ID 7/13/2015 7/14/2014
A 1 20 30
A 2 30 50
A total 50 80
B 3 50 70
B 4 60 30
C 5 20 30
C 6 30 80
C 7 10 30
我知道如何创建新行并添加名称和 ID,但我可以使用 c# 模块来计算特定总和。我抬头一看,他们是 table_name.Compute();但我在实施时遇到错误。
- 请注意,列全名的值带有 space,并且该列中的值也可以包含 space。
这是一个 return 新的 object[]
函数,它将给定 table 中的每一行与给定列索引中的指定值进行匹配。匹配的行在所有其他列上求和,总和在相应的索引中 returned。
private object[] GetSumRow(DataTable table, string nameToMatchAgainst, int nameColumnIndex = 0)
{
object[] sumRow = new object[table.Columns.Count];
IEnumerable<DataRow> rows = table.Rows.Cast<DataRow>().Where(r => r[nameColumnIndex].ToString() == nameToMatchAgainst);
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == nameColumnIndex)
{
sumRow[i] = nameToMatchAgainst;
}
else
{
sumRow[i] = rows.Sum(r => int.Parse(r[i].ToString()));
}
}
return sumRow;
}
因此调用 var sumRow = GetSumRow(yourExampleTable, "A")
会 return ["A", 3, 50, 80]
,然后您可以使用 yourExampleTable.Rows.Add(sumRow)
.