简体   繁体   中英

How to find the empty cells in the datatable and replace with 0

I am working with a very large datatable which has 5000 rows and 8000 columns. In the data table there are some empty cells. I use the following code to fill the empty cells with 0. But since the datatable is very large, the speed is really slow!!! I just want to ask if there are some other ways instead of the for loop.

for (int i = 0; i < SP_dt.Rows.Count; i++)
{
    for (int j = 0; j < SP_dt.Columns.Count; j++)
    {
        if (SP_dt.Rows[i][j].ToString() == "")
            SP_dt.Rows[i][j] = 0;
        Console.WriteLine("{0}  {1}",i,j);
    }

}

The problem is better solved in the SQL than in C# code, create a stored procedure for your query, and then use COALESCE system function.

The COALESCE function will basically check a set of elements given in its arguments from the left to right till it finds that it is not NULL and returns it. This way, you could put your default value 0 in the last element of COALESCE :

create procedure spMyProc
as
begin
  select 
    COALESCE(colName1HavingNumericDataTypeToBeChecked, 0),
    COALESCE(colName2HavingNumericDataTypeToBeChecked, 0), 
    COALESCE(colNameNHavingNumericDataTypeToBeChecked, 0) 
  from tableName
end

Then in your C# code, you just call that stored procedure .

If your colName1HavingNumericDataTypeToBeChecked is not NULL , it will return the value in the colName1HavingNumericDataTypeToBeChecked . If it is NULL , then it will look up the next item and find 0 (which is not NULL ) and it will return 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM