去除DataTable中的重复行

本文介绍了一种通过指定字段过滤DataTable中重复行的方法。该方法首先复制原始DataTable,然后按指定字段进行排序,并移除重复记录,保留唯一数据。

                #region   过滤DataTable中的指定字段重复的行

                ///   <summary>
                ///   过滤DataTable中的指定字段重复的行
                ///   </summary>
                ///   <param   name= "dt "> </param>
                ///   <param   name= "FieldName "> </param>
                ///   <returns> </returns>
                public   DataTable   SelectDistinctByField(DataTable   dt,   string   FieldName)
                {
                        DataTable   returnDt   =   new   DataTable();
                        returnDt   =   dt.Copy();//将原DataTable复制一个新的
                        DataRow[]   drs   =   returnDt.Select( " ",   FieldName);//将DataTable按指定的字段排序
                        object   LastValue   =   null;  
                        for(int   i   =   0;   i   <   drs.Length;   i++)
                        {
                                if((LastValue   ==   null)   ||   (!(ColumnEqual(LastValue,   drs[i][FieldName]))))
                                {
                                        LastValue   =   drs[i][FieldName];  
                                        continue;          
                                }
         
                                drs[i].Delete();
                        }
 
                        return   returnDt;
                }

                private   bool   ColumnEqual(object   A,   object   B)
                {  
                        //   Compares   two   values   to   see   if   they   are   equal.   Also   compares   DBNULL.Value.
                        //   Note:   If   your   DataTable   contains   object   fields,   then   you   must   extend   this
                        //   function   to   handle   them   in   a   meaningful   way   if   you   intend   to   group   on   them.
     
                        if   (   A   ==   DBNull.Value   &&   B   ==   DBNull.Value   )   //     both   are   DBNull.Value
                                return   true;  
                        if   (   A   ==   DBNull.Value   ||   B   ==   DBNull.Value   )   //     only   one   is   DBNull.Value
                                return   false;  
                        return   (   A.Equals(B)   );     //   value   type   standard   comparison
                }

                #endregion

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值