C#替换数据表中的值

时间:2018-06-28 09:38:10

标签: c# loops foreach datatable

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

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

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

alias gdca='git diff --cached' # diff between your staged file and the last commit
alias gdcc='git diff HEAD{,^}' # diff between your recent tow commits

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

1 个答案:

答案 0 :(得分:1)

您无法对原始表执行此操作,因为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;
}