Today, a friend asked me how to remove the repeated records in the datatable. (The datatable is returned by someone else and cannot query the database again. Therefore, the Select distinct XXX in SQL cannot be used for processing, you can only use your mind on datatable)
Idea: Convert datatable to ienumerable, and then you can call the distinct method.
By poplar http://yjmyzz.cnblogs.com under the bodhi tree/
Using System. Collections. Generic;
Using System. LINQ;
Using System. Data;
Using System;
Namespace Leleapplication2
{
Class Program
{
Static Void Main ( String [] ARGs)
{
Datatable TBL = New Datatable ();
TBL. Columns. Add ( " ID " , Typeof (System. int32 ));
TBL. Columns. Add ( " City " , Typeof (System. String ));
TBL. Columns. Add ( " Province " , Typeof (System. String ));
TBL. Rows. Add ( 1 , " Wuhan " , " Hubei Province " );
TBL. Rows. Add ( 2 , " Yingcheng " , " Hubei Province " );
TBL. Rows. Add ( 3 , " Wuhan " , " Hubei Province " );
Ienumerable<Datarow>R=TBL. asenumerable (). Distinct (NewCitycomparer ());
// In this step, the record is repeated in R.
Foreach (VAR item In R)
{
Console. writeline (item [ " ID " ] + " , " + Item [ " City " ] + " , " + Item [ " Province " ]);
}
Console. Readline ();
}
}
Class Citycomparer: iequalitycomparer < Datarow >
{
Public Bool Equals (datarow R1, datarow R2)
{
Return R1 [ " City " ] = R2 [ " City " ];
}
Public IntGethashcode (datarow OBJ)
{
ReturnOBJ. tostring (). gethashcode ();
}
}
}
The aboveCodeRemove the record with duplicate "city name" in datatable. The code above applies to list <t> (just change it to "comparator)