DataTable removes duplicate rows and performs distinct based on a field. datatabledistinct
There are many methods on the Internet, such as using view processing:
// Remove the duplicate row DataView dv = table. defaultView; table = dv. toTable (true, new string [] {"name", "code"}); in this case, the table has only two rows with no duplicate names and codes, if the id value is also required, table = dv. toTable (true, new string [] {"id", "name", "code"}); // The first parameter true enables deduplication, similar to distinct
But there is a problem with this method, that is, as long as I filter duplicates by id but keep other fields, this method does not work.
New method:
DataTable dt = new DataTable ();
Dt. Columns. Add ("id ");
Dt. Columns. Add ("name ");
Dt. Columns. Add ("pro ");
Dt. Rows. Add (new object [] {"1", "1", "11 "});
Dt. Rows. Add (new object [] {"1", "2", "111 "});
Dt. Rows. Add (new object [] {"1", "3", "1111 "});
Dt. Rows. Add (new object [] {"1", "4", "11111 "});
Dt. Rows. Add (new object [] {"2", "1", "111111 "});
Dt. Rows. Add (new object [] {"1", "2", "1111111 "});
DataRow [] drs = dt. Copy (). Select ("", "id ");
// Store all specifications (no duplicates)
Object value = null;
DataTable d = dt. Clone ();
For (int I = 0; I <drs. Length; I ++)
{
If (value = null |! Value. Equals (drs [I] ["id"]. ToString ()))
{
D. ImportRow (drs [I]);
Value = drs [I] ["id"]. ToString ();
Continue;
}
Drs [I]. Delete ();
}
The final d is to filter the duplicate results based on the id.