[英]How to Delete DataRow from DataTable quickly
I input data in DataTable in column direction. 我在数据表中沿列方向输入数据。
for(int i=0 ; i<mTable.Count ; i++){
Table.Columns.Add(i);
foreach(DataRow row in Table.Rows){
if(result == 1)
row[i] = result;
else
row[i] = null;
}
}
From here, If All data of column is null, I want to delete row. 从这里开始,如果column的All data为null,我想删除行。
For example, 例如,
1 2 3 4 5 1 2 3 4 5
6 7 8 9 10 6 7 8 9 10
11 12 13 14 15 11 12 13 14 15
16 17 18 19 20 16 17 18 19 20
11, 12, 13, 14, 15 are null, I want to delete Table.Rows[2]. 11,12,13,14,15为null,我想删除Table.Rows [2]。
So, I use next way. 所以,我使用下一种方式。
for(int i = Table.Rows.Count-1;i >= 0;i--)
{
for (int j = 0; j < mTable.Count; j++)
{
if (Table.Rows[i][j] != null)
break;
if(j == mTable.Count-1)
Table.Rows.Remove(Table.Rows[i]);
}
}
But, If There's a lot of data, It will slow down considerably. 但是,如果有大量数据,它将大大降低速度。
Is there another fast way? 还有另一种快速方法吗?
You algorithm is probably the quickest method. 您的算法可能是最快的方法。 But you can can a little bit better performance with a few improvements 但是您可以通过一些改进来提高性能
int numberOfCols = Table.Columns.Count;
for (int i = Table.Rows.Count - 1; i >= 0; i--)
{
Boolean delete = true;
for (int j = 0; j < numberOfCols; j++)
{
if (Table.Rows[i][j] != null)
{
delete = false;
break;
}
}
if (delete)
{
Table.Rows.Remove(Table.Rows[i]);
}
}
Instead of deleting the rows, you can select the non null rows from your table. 您可以从表中选择非空行,而不是删除行。
public void DtSelect()
{
var dt = new DataTable();
var columns = Enumerable.Range(1, 10).Select(x => "Col" + x).ToList();
columns.ForEach(x => dt.Columns.Add(x));
Enumerable.Range(1, 1000).ToList().ForEach(x =>
{
var row = dt.NewRow();
if (x % 15 == 0) columns.ForEach(z => row[z] = x);
dt.Rows.Add(row);
});
var query = "(" + string.Join(" is not null) or (", columns) + " is not null)";
var nonEmpty = dt.Select(query).CopyToDataTable();
}
nonEmpty
will not be a datatable with all rows that are non empty; nonEmpty
将不是所有非空行的数据表;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.