C# 替换数据表中的值



如果数据表中的整数值大于 0 且小于 5,则需要用字符串符号 (*( 替换它们。

到目前为止,我可以遍历每一行和相应的列,但我无法获取数据表中包含的各个值。

到目前为止,我编写的代码如下所示:

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

如何获取值然后替换它们?

不能对原始表执行此操作,因为intdouble列不是string列。您需要一个新表,其中每个数字列都替换为一个字符串列:

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;
}

最新更新