Reputation: 796
I need to replace integers values inside a datatable with a string symbol (*) if they are greater than 0 and less than 5.
So far I can loop through each row and the corresponding columns but I am unable to get the individual values contained in the datatable.
The code I have written so far is shown below:
public static DataTable SupressDataTable(DataTable cases)
{
DataTable suppressedDataTable = new DataTable();
foreach (var row in cases.Rows)
{
foreach (DataColumn column in cases.Columns)
{
if (column.IsNumeric())
{
}
}
}
return suppressedDataTable;
}
public static bool IsNumeric(this DataColumn col)
{
if (col == null)
return false;
// Make this const
var numericTypes = new[] { typeof(Byte), typeof(Decimal), typeof(Double),
typeof(Int16), typeof(Int32), typeof(Int64), typeof(SByte),
typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64)};
return ((IList) numericTypes).Contains(col.DataType);
}
How do I get to the values and then replace them?
Upvotes: 1
Views: 1339
Reputation: 460288
You can't do that with the original table because an int
or double
column is not a string
column. You need a new table where each numeric column is replaced with a string column:
public static DataTable SupressDataTable(DataTable cases)
{
DataTable suppressedDataTable = cases.Copy(); // Same columns, same data
DataColumn[] allNumericColumns = suppressedDataTable.Columns.Cast<DataColumn>().Where(IsNumeric).ToArray();
foreach (DataColumn numericCol in allNumericColumns)
{
int ordinal = numericCol.Ordinal; // need to store before remove
suppressedDataTable.Columns.Remove(numericCol);
suppressedDataTable.Columns.Add(numericCol.ColumnName); // string column
suppressedDataTable.Columns[numericCol.ColumnName].SetOrdinal(ordinal);
}
for (int index = 0; index < suppressedDataTable.Rows.Count; index++)
{
DataRow row = suppressedDataTable.Rows[index];
foreach (DataColumn column in cases.Columns)
{
if (IsNumeric(column))
{
dynamic numVal = cases.Rows[index][column];
string newValue = numVal > 0 && numVal < 5 ? "*" : numVal.ToString();
row.SetField(column.Ordinal, newValue);
}
}
}
return suppressedDataTable;
}
Upvotes: 1