zoukankan      html  css  js  c++  java
  • DataTable 根据某个字段过滤掉重复记录

    DataTable 根据某个字段过滤掉重复记录

         如果是在数据库 你当然可以     select distinct name   然而你如果和我一样不幸的只能处理一个DataTable

    方案1:

                //DataView dv = new DataView(dt);
                //dv.RowFilter = "select distinct processname ";
                //return dv;

    然而这是不行的,RowFilter 貌似不支持这样写

    方法2:
                //DataTable dv = dt;//.DefaultView.ToTable(true, new string[]{列名1,列明2,... });
                //return dv;

    可这样你得知道所有列名,还无法根据某个字段筛选。
               

    方法3:我最后用的。

    return SelectDistinctByField(dt, "processname");

         #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

    zz:http://hi.baidu.com/cnhifhtbibbcrvd/item/a23727c02fe904c4984aa0b0

  • 相关阅读:
    Delphi 访问https /SSL、OpenSSL
    Delphi UTF编码/解码 UTF8Encode、UTF8Decode、URLEncode、URLDecode
    编译器架构Compiler Architecture(下)
    编译器架构Compiler Architecture(上)
    Xilinx Zynq FPGA Boards板
    如何为应用选择最佳的FPGA(下)
    如何为应用选择最佳的FPGA(上)
    FPGA与ASIC:它们之间的区别以及使用哪一种?
    ASIC设计-终极指南
    77GHz 和24GHz Radar性能解析
  • 原文地址:https://www.cnblogs.com/activities/p/2694767.html
Copyright © 2011-2022 走看看