C#从数据表中删除所有值都为零的列
本文关键字:数据表 删除 | 更新日期: 2024-09-23 04:16:54
我需要从数据表中删除所有行都为0的列。或者换句话说,其中sum为0。
1 2 5 99.9 442.25 221 0
1 2 77.7 889 898 55 0
9 0 66 42 55 0 0
在本例中,应删除最后一列。
如何做到这一点?
DataTable dt;
int dataWidth = 5; //use a loop or something to determine how many columns will have data
bool[] emptyCols = new bool[datawidth]; //initialize all values to true
foreach(Row r in dt)
{
for(int i = 0; i < dataWidth; i++)
{
if(r[i].Contents != 0))
emptyCols[i] = false;
}
}
for(int i = 0; i < emptyCols.Length; i++)
{
if(emptyCols[i])
dt.Columns.RemoveAt(i);
}
我还没有测试过,但我已经用excel列做过类似的事情。基本逻辑就在那里,我不知道我的所有增量或行编号是否都是正确的。我相信我使用的大多数功能也是可用的。
第一个:
protected Boolean IsColumnZero(DataTable dt, string columnName)
{
foreach (DataRow row in dt.Rows)
if ((int)row[columnName] != 0) return false;
return true;
}
然后你可以:
//create table
DataTable table = new DataTable();
table.Columns.Add("caliber", typeof(int));
table.Columns.Add("barrel", typeof(int));
table.Rows.Add(762, 0);
table.Rows.Add(556, 0);
table.Rows.Add(900, 0);
//delete zero value columns
List<string> columnsToDelete = new List<string>();
foreach (DataColumn column in table.Columns)
if (IsColumnZero(table, column.ColumnName))
columnsToDelete.Add(column.ColumnName);
foreach (string ctd in columnsToDelete) table.Columns.Remove(ctd);
//show results
GridView1.DataSource = table;
GridView1.DataBind();