# Region filters rows with duplicate fields in the DataTable.
/// <Summary>
/// Filter the rows with duplicate fields in the 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 (); // Copy the original able to a new
DataRow [] drs = returnDt. Select ("", FieldName); // sort the DataTable by specified field
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
From chinaboykai