【问题标题】:Replace DataRow value with empty string if duplicate in DataTable如果 DataTable 中重复,则将 DataRow 值替换为空字符串
【发布时间】:2015-10-15 02:22:53
【问题描述】:

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

例如

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

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

【问题讨论】:

  • 到目前为止你有没有尝试过?
  • 不,但我最初想在我的存储过程中执行此操作,但用户建议我在有意义的应用程序层执行此操作。我正在考虑迭代数据行,但我想这不是一个好主意。 stackoverflow.com/questions/33138663/…
  • 此解决方案适用于 gridview,但可能会有所帮助。 codeproject.com/Articles/34337/…
  • 谢谢,我根据你的回答写了一个扩展。
  • 应用层并不一定意味着数据表/数据网格。报告工具会自动为您完成。

标签: c# datatable


【解决方案1】:

我为此写了一个扩展。

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

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 2022-11-12
    • 2014-11-12
    • 2017-05-01
    • 1970-01-01
    • 2014-08-10
    • 2012-09-15
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多