【问题标题】:C# replace values in a DatatableC# 替换数据表中的值
【发布时间】:2018-06-28 09:38:09
【问题描述】:

如果数据表中的整数值大于 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
  • 所以我需要将数字列转换为字符串?

标签: c# loops foreach datatable


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 2021-07-17
    • 2017-08-06
    • 2016-06-08
    • 1970-01-01
    相关资源
    最近更新 更多