In the actual development process, many people may have encountered the same requirements:
You need to obtain different values contained in one or more columns of the datatable to obtain results similar to group by in SQL.
1. The traditional method is to traverse the able (. NET Framework versions are common)
/// Select non-repeated rows from sourcetable according to fieldname, /// equivalent to select distinct fieldname1, fieldname2 ,, fieldnamen from sourcetable /// </Summary> /// <Param name = "tablename"> table name </param> /// <Param name = "sourcetable"> source datatable </param> /// <Param name = "fieldnames"> column name array </param> /// <returns> A new able without duplicate rows, the columns only include the columns specified in 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 sourcetabl E. 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. SimpleCodeImplementation Method (only applicable to. Net framework2.0 and later versions)
Datatable sourcetable = New Soursetable (); sourcetable. Columns. Add ( " Code " , String ); // ... Add data to soursetable Dataview View = New Dataview (sourcetable ); String [] Columns = { " Code " }
Datatable tartable=View. totable (True, Columns );//Get target
3. Use LINQ to SQL (applicable only to. Net framework3.5 and later versions)
Looking at this Internet from the perspective of discovery, there is always a place where we can stand! -- North latitude 28.33