zoukankan      html  css  js  c++  java
  • 去除DataTable重复数据的三种方法

    其中要避免目标库插入重复数据。这重复数据可能是源数据库本身就有重复数据,还有就是已经插入避免重复插入。

    过滤自身重复数据解决方案

    第一种:采用DataView.ToTable()方法

    DataView.ToTable 方法

    .NET Framework 2.0
     
    根据现有 DataView 中的行,创建并返回一个新的 DataTable

    重载列表

     
    名称说明
    DataView.ToTable () 根据现有 DataView 中的行,创建并返回一个新的 DataTable

    由 .NET Compact Framework 支持。

    DataView.ToTable (String) 根据现有 DataView 中的行,创建并返回一个新的 DataTable

    由 .NET Compact Framework 支持。

    DataView.ToTable (Boolean, String[]) 根据现有 DataView 中的行,创建并返回一个新的 DataTable

    由 .NET Compact Framework 支持。

    DataView.ToTable (String, Boolean, String[]) 根据现有 DataView 中的行,创建并返回一个新的 DataTable

    由 .NET Compact Framework 支持。

    实例代码

    复制代码
     public static DataTable Distinct(DataTable dt, string[] filedNames)
            {
                DataView dv = dt.DefaultView;
                DataTable DistTable = dv.ToTable("Dist", true, filedNames);
                return DistTable;
            }
    复制代码

    第二种方法:循环遍历+DataTable.Select()

    利用for循环遍历DataTable的数据行,利用DataTable.Select 方法判断是否重复,如果重复,则利用DataTable.Rows.RemoveAt(Index)删除重复的那一行。

    具体看代码。

    代码示例

    复制代码
     public DataTable GetDistinctSelf(DataTable SourceDt, string filedName)
            {
     for (int i = SourceDt.Rows.Count - 2; i > 0; i--)
                {
                    DataRow[] rows = SourceDt.Select(string.Format("{0}='{1}'", filedName, SourceDt.Rows[i][filedName]));
                    if (rows.Length > 1)
                    {
                        SourceDt.Rows.RemoveAt(i);
                    }
                }
             return SourceDt;
    
            
            }
    复制代码

    第三种方法

    利用双循环遍历(不推荐)

    复制代码
     public DataTable GetDistinctSelf(DataTable SourceDt, string filedName)
            {
                for (int i = SourceDt.Rows.Count - 2; i > 0; i--)
                {
                    string title = SourceDt.Rows[0][filedName].ToString();
                    for (int j = i + 1; j > 0; i--)
                    {
                        if (SourceDt.Rows[j][filedName].ToString() == title)
                        {
                            SourceDt.Rows.RemoveAt(i);
    
                        }
                    }
    
                }
                return SourceDt;
              }
    复制代码
  • 相关阅读:
    训练1-J
    训练1-K
    训练1-P
    二分查找法详解
    POJ:1094-Sorting It All Out(拓扑排序经典题型)
    POJ:2632-Crashing Robots
    POJ:1086-Parencodings
    POJ:2586-Y2K Accounting Bug
    POJ:2109-Power of Cryptography(关于double的误差)
    POJ:1328-Radar Installation
  • 原文地址:https://www.cnblogs.com/Fooo/p/6666825.html
Copyright © 2011-2022 走看看