The distinct processing of data in datatable is similar to select distinct (field1, field2) from sourcetable (arlenliu) # Region The distinct processing of data in datatable is similar to select distinct (field1, field2) from sourcetable (arlenliu)
Public Datatable selectdistinct (datatable sourcetable, Params String [] Fieldnames)
{
Object [] Lastvalues;
Datatable newtable;
Datarow [] orderedrows;
If (Fieldnames = Null | Fieldnames. Length = 0 )
Throw New Argumentnullexception ( " Fieldnames " );
Lastvalues = New Object [Fieldnames. Length];
Newtable = New Datatable ();
Foreach ( String Fieldname In Fieldnames)
Newtable. Columns. Add (fieldname, sourcetable. Columns [fieldname]. datatype );
Orderedrows = Sourcetable. Select ( "" , String . Join ( " , " , Fieldnames ));
Foreach (Datarow row In Orderedrows)
{
If ( ! Fieldvaluesareequal (lastvalues, row, fieldnames ))
{
Newtable. Rows. Add (createrowclone (row, newtable. newrow (), fieldnames ));
Setlastvalues (lastvalues, row, fieldnames );
}
}
Return Newtable;
}
Private Bool Fieldvaluesareequal ( Object [] Lastvalues, datarow currentrow, String [] Fieldnames)
{
Bool Areequal = True ;
For ( Int I = 0 ; I < Fieldnames. length; I ++ )
{
If (Lastvalues [I] = Null | ! Lastvalues [I]. Equals (currentrow [fieldnames [I])
{
Areequal= False;
Break;
}
}
Return Areequal;
}
Private Datarow createrowclone (datarow sourcerow, datarow newrow, String [] Fieldnames)
{
Foreach(StringFieldInFieldnames)
Newrow [field]=Sourcerow [field];
ReturnNewrow;
}
Private Void Setlastvalues ( Object [] Lastvalues, datarow sourcerow, String [] Fieldnames)
{< br> for ( int I = 0 ; I fieldnames. length; I ++ )
lastvalues [I] = sourcerow [fieldnames [I];
}
# Endregion
I don't know where it is. It's easy to use.