DataTable and List methods for deduplication
Idea: Convert DataTable to IEnumerable, and then you can call the Distinct method.
Reproduced from: Under the bodhi tree Yang Guo http://yjmyzz.cnblogs.com/
Using System. Collections. Generic;
Using System. Linq;
Using System. Data;
Using System;
Namespace ConsoleApplication2
{
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 ");
Tbl. Rows. Add (2, "Yingcheng", "Hubei ");
Tbl. Rows. Add (3, "Wuhan", "Hubei ");
IEnumerable <DataRow> r = tbl. AsEnumerable (). Distinct (new CityComparer ());
// 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 int GetHashCode (DataRow obj)
{
Return obj. ToString (). GetHashCode ();
}
}
}