ADO.NET 從DataTable中擷取某列含有的不重複值的幾種方式

來源:互聯網
上載者:User
 

在實際開發過程中也許不少人也遇到過我同樣的需求:

需要擷取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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.