dataTable distinct

     DataView DV = dtLineTypeURL.DefaultView;
     DataTable dtTmp = DV.ToTable("tb1", true, "LineType"); // 对 LineType 使用distinct
     dtLineTypeURL = dtTmp;


    dtLineTypeURL = dtLineTypeURL.DefaultView.ToTable(true, "LineType"); // 对 LineType 使用distinct

注意:通过以上方式 得到的dataTable 仅有LineType这一列,其它列都被丢弃了。


如果 只是希望 针对某一列做 distinct, 其它列保留,则用下面的:

       #region 删除DataTable重复列,类似distinct
       /// <summary>
       /// 删除DataTable重复列,类似distinct
       /// </summary>
       /// <param name="dt">DataTable</param>
       /// <param name="Field">字段名</param>
       /// <returns></returns>
       public static DataTable DeleteSameRow(DataTable dt, string Field)
       {
           ArrayList indexList = new ArrayList();
           // 找出待删除的行索引
           for (int i = 0; i < dt.Rows.Count - 1; i++)
           {
               if (!indexList.Contains(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);
                       }
                   }
               }
           }

           indexList.Sort();

           // 根据待删除索引列表删除行
           for (int i = indexList.Count - 1; i >= 0; i--)
           {
               int index = Convert.ToInt32(indexList[i]);
               dt.Rows.RemoveAt(index);
           }
           return dt;
       }
 
       #endregion 


调用方法:

  dtLineTypeURL = Common.DeleteSameRow(dtLineTypeURL, "LineType");// 对 LineType 使用distinct


题外话:

         针对 List 去重:   IList<int> nlist = list.Distinct().ToList();
         针对3个List,    排除一个List A中 所有的List B的项: lstKeywordsNotExisting = lstKeywords.Except(lstKeywordsExisting).ToList();

参考:http://blog.csdn.net/smartsmile2012/article/details/7903846

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值