如果DataTable中重复,则将DataRow值替换为空字符串



是否可以用空字符串替换行值,如果发现重复的值?

例如

--------------------
ProductCode | Color
--------------------
   00A0B    |  Red
   00A0B    |  Blue
   00A0C    |  Red
   00A0C    |  Black
   00A0C    |  White
--------------------

--------------------
ProductCode | Color
--------------------
   00A0B    |  Red
            |  Blue
   00A0C    |  Red
            |  Black
            |  White
--------------------

我为此写了一个扩展。

    public static DataTable Dedup(this DataTable dt, string columnName)
    {
        for (int rowIndex = dt.Rows.Count - 1; rowIndex >= 1; rowIndex--)
        {
            var row = dt.Rows[rowIndex][columnName];
            var previousRow = dt.Rows[rowIndex - 1][columnName];
            if (row.ToString() == previousRow.ToString())
            {
                dt.Rows[rowIndex][columnName] = "";
            }
        }
        return dt;
    }

如何使用:

DataTable dt = _product.GetProduct();
dt.Dedup("ProductCode");

最新更新