2012-08-03 104 views
-2

我需要从数据表中删除所有行的值为0的列。或者换句话说,当总和为0。C#从所有值为零的数据表中删除列

1 2 5 99.9 442.25 221 0 
1 2 77.7 889 898  55 0 
9 0 66 42 55  0 0 

在这个例子中,最后一列应被删除。

如何做到这一点?

+0

更具体与您的问题 – MethodMan 2012-08-03 21:20:25

+1

“或者换句话说,当总和为0。”这不仅仅是“其他的词”,这是完全不同的事情(想想一个有一些正面价值观和一些负面价值观的专栏)。 – dasblinkenlight 2012-08-03 21:21:11

+0

@dasblinkenlight他们不应该是负面的。但让我们忽略其他的话。 – 2012-08-03 21:22:32

回答

1
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列类似的东西。基本逻辑在那里,我不知道我的所有增量或行编号是否完全正确。我相信我使用的大部分功能都可以使用。

1

第一:

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();