栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

删除DataTable重复列,只删除其中的一列重复行的解决方法

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

删除DataTable重复列,只删除其中的一列重复行的解决方法

vs2005针对datatable已经有封装好的去重复方法:
复制代码 代码如下:
//去掉重复行
 DataView dv = table.DefaultView;
 table = dv.ToTable(true, new string[] { "name", "code" });

 此时table 就只有name、code无重复的两行了,如果还需要id值则

 table = dv.ToTable(true, new string[] { "id","name", "code" });//第一个参数true 启用去重复,类似distinct

如果有一组数据(id不是唯一字段)

复制代码 代码如下:
id   name   code
    张三    123
    李四    456
    张三    456
   张三     123

通过上面的方法得到

复制代码 代码如下:
id   name   code
    张三    123
    李四    456
    张三    456

去重复去掉的仅仅是 id name code完全重复的行,如果想要筛选的数据仅仅是name不允许重复呢?

复制代码 代码如下:
table = dv.ToTable(true, new string[] { "name"});

得到:

复制代码 代码如下:
name

张三 

李四 

但是我想要的结果是只针对其中的一列name列 去重复,还要显示其他的列

需要的结果是:

复制代码 代码如下:
 id   name   code


1    张三    123

2    李四    456

这个该怎么实现?下面的方法就可以,也许有更好的方法,希望大家多多指教

复制代码 代码如下:
#region 删除DataTable重复列,类似distinct
         ///

  
         /// 删除DataTable重复列,类似distinct  
         ///
  
         /// DataTable  
         /// 字段名  
         ///   
         public static DataTable DeleteSameRow(DataTable dt, string Field)
         {
             ArrayList indexList = new ArrayList();
             // 找出待删除的行索引  
             for (int i = 0; i < dt.Rows.Count - 1; i++)
             {
                 if (!IsContain(indexList, i))
                 {
                     for (int j = i + 1; j < dt.Rows.Count; j++)
                     {
                         if (dt.Rows[i][Field].ToString() == dt.Rows[j][Field].ToString())
                         {
                             indexList.Add(j);
                         }
                     }
                 }
             }
             // 根据待删除索引列表删除行  
             for (int i = indexList.Count - 1; i >= 0; i--)
             {
                 int index = Convert.ToInt32(indexList[i]);
                 dt.Rows.RemoveAt(index);
             }
             return dt;
         }

         ///   
         /// 判断数组中是否存在  
         ///
  
         /// 数组  
         /// 索引  
         ///   
         public static bool IsContain(ArrayList indexList, int index)
         {
             for (int i = 0; i < indexList.Count; i++)
             {
                 int tempIndex = Convert.ToInt32(indexList[i]);
                 if (tempIndex == index)
                 {
                     return true;
                 }
             }
             return false;
         }
         #endregion

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/58017.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号