4

ご存知のように、datatableの計算関数を使用すると、列の合計を取得できます。しかし、データテーブルの行の合計を取得したいと思います。例を挙げて説明します。

以下の画像のようなデータテーブルがあります。計算関数を使用すると、各列(積)の合計を取得できます。product1の場合など、2 + 12 + 50 + 13=77。

company1の合計を取得したい:2 + 6 + 4 + 3 + 5 = 20

http://img123.imageshack.us/img123/1517/61519307xx5.jpg

どうすればasp.net1.1でそれを行うことができますか?

4

4 に答える 4

2

救助のためのLINQ:

DataTable dt = WhateverCreatesDataTable();
DataRow dr = dt.Rows[0];
int sum = dt.Columns.Cast<DataColumn>().Sum(dc=>(int)dr[dc]);

石器時代(別名pre-.Net 3.5およびLINQ)でまだナックルをドラッグしている人のために:

DataTable dt = WhateverCreatesDataTable();
DataRow dr = dt.Rows[0];
int sum = 0;

foreach(DataColumn dc in dt.Columns)
  sum += (int)dr[dc];
于 2008-12-05T15:52:59.657 に答える
2

msdnから:

2つ以上の列で操作を実行する必要がある場合は、DataColumnを作成し、そのExpressionプロパティを適切な式に設定して、結果の列で集計式を使用する必要があります。その場合、「total」という名前のDataColumnを指定し、Expressionプロパティを次のように設定します。

"Quantity * UnitPrice"

于 2008-12-05T15:40:16.797 に答える
2

これを1.1で解決したいので、簡単な解決策としてできることは次のとおりです

DataColumn totalColumn = new DataColumn();
totalColumn.DataType = System.Type.GetType("System.Int32");
totalColumn.ColumnName = "Total";
totalColumn.Expression = "Product1 + Product2 + Product3 + Product4 + Product5";

// Populate and get the DataTable dt then add this computed column to this table

dt.Columns.Add(totalColumn);
//Now if you access the column "Total" of the table you will get the desired result.
于 2009-01-07T17:18:21.093 に答える