zoukankan      html  css  js  c++  java
  • ADO.NET 从DataTable中获取某列含有的不重复值的几种方式

     

    在实际开发过程中也许不少人也遇到过我同样的需求:

    需要获取DataTable中某一列或几列的含有的不同值,得到类似SQL中Group By的结果

    1、传统做法是遍历DataTable(.NET Framework个版本通用) 

     

     /// 按照fieldName从sourceTable中选择出不重复的行, 
            /// 相当于select distinct fieldName1,fieldName2,,fieldNamen from sourceTable 
            /// </summary> 
            /// <param name="tableName">表名</param> 
            /// <param name="sourceTable">源DataTable</param> 
            /// <param name="fieldNames">列名数组</param> 
            /// <returns>一个新的不含重复行的DataTable,列只包括fieldNames中指明的列</returns> 
            public DataTable SelectDistinct(string tableName, DataTable sourceTable, string[] fieldNames) 
            { 
                DataTable dt = new DataTable( tableName ); 
                object[] values = new object[fieldNames.Length]; 
                string fields = ""; 
                for ( int i = 0; i < fieldNames.Length; i++ ) 
                { 
                    dt.Columns.Add( fieldNames[ i ], sourceTable.Columns[ fieldNames[ i ] ].DataType ); 
                    fields += fieldNames[ i ] + ","; 
                } 
                fields = fields.Remove( fields.Length - 1, 1 ); 
                DataRow lastRow = null; 
                foreach ( DataRow dr in sourceTable.Select( "", fields ) ) 
                { 
                    if ( lastRow == null || !( RowEqual( lastRow, dr, dt.Columns ) ) ) 
                    { 
                        lastRow = dr; 
                        for ( int i = 0; i < fieldNames.Length; i++ ) 
                        { 
                            values[ i ] = dr[ fieldNames[ i ] ]; 
                        } 
                        dt.Rows.Add( values ); 
                    } 
                } 
                if ( ds != null && !ds.Tables.Contains( tableName ) ) 
                { 
                    ds.Tables.Add( dt ); 
                } 
                return dt; 
    
           } 
    

      

          

    2、简单代码实现方式(只适用于.NET Framework2.0及以后版本)

    复制代码
    DataTable SourceTable =new SourseTable(); SourceTable.Columns.Add("Code",string); //...向SourseTable中添加数据DataView view =new DataView(SourceTable); string[] columns = {"Code"}

    DataTable tarTable = view.ToTable(true,columns);//得到目标

    复制代码

    3、使用Linq to Sql(只适用于.NET Framework3.5及以后版本)

    用发现的眼光来看这个互联网,总有我们立脚的地方!——北纬28.33

  • 相关阅读:
    实现textFiel和textView中的键盘的关闭
    Objective-C语法之动态类型
    设置APP的启动图片(Launch Image)
    iOS开发中学到的技巧
    CorePlot学习 坐标轴的详细分析
    CorePlot学习 点击scatterPlot中的symbol点时弹出相应的注释
    CorePlot学习 使用技巧
    [转载]core-Plot学习二 自定义CorePlot label及majorGridLine莫名其妙消失的Bug
    Core-Plot学习一 基本对象、添加库
    AFNetworking2.5使用
  • 原文地址:https://www.cnblogs.com/xiaofengfeng/p/2674959.html
Copyright © 2011-2022 走看看