代码改变世界

删除datatable的重复行

2013-04-25 23:31  hongjiumu  阅读(305)  评论(7编辑  收藏  举报

删除datatable的重复行

private void RemoveRepeat(ref System.Data.DataTable dataTableSource)
        {
            List<string> list = new List<string>();
            StringBuilder builder = null;
            System.Data.DataRow currenDr = null;
            string currentStr = string.Empty;
            for (int i = dataTableSource.Rows.Count-1; i >= 0;i-- )
            {
                if (dataTableSource.Rows[i]==null)
                {
                    continue;
                }
                currenDr=dataTableSource.Rows[i];
                builder = new StringBuilder();
                for (int j = 0; j < dataTableSource.Columns.Count;j++ )
                {
                    builder.AppendFormat("{0}={1}", 
                            dataTableSource.Columns[j].ColumnName,
                            currenDr[dataTableSource.Columns[j].ColumnName] == DBNull.Value ?
                                "NULL" : 
                                currenDr[dataTableSource.Columns[j].ColumnName].ToString()
                        );
                    if (j < dataTableSource.Columns.Count-1)
                    {
                        builder.Append(",");
                    }
                }
                currentStr = builder.ToString().Trim();
 
                if (!list.Contains(currentStr))
                {
                    list.Add(currentStr);
                }
                else
                {
                    dataTableSource.Rows.RemoveAt(i);
                    dataTableSource.AcceptChanges();
                }
            }
        }