Delete a repeated DataTable column. Only duplicate rows in one of the columns are deleted. One datatable Column
Vs2005 has encapsulated deduplication methods for datatable:
1 // remove duplicate rows 2 DataView dv = table. defaultView; 3 table = dv. toTable (true, new string [] {"name", "code"}); 4 5 at this time, the table only has two rows: name and code, if the id value is also required, 6 7 table = dv. toTable (true, new string [] {"id", "name", "code"}); // The first parameter true enables deduplication, similar to distinct
If there is a set of data (id is not a unique field)
Id name code1 Zhang San 1232 Li Si 4563 Zhang San 4561 Zhang San 123
Obtain
Id name code1 Zhang San 1232 Li Si 4563 Zhang San 456
Deduplication removes only the rows whose id name code is completely duplicated. What if the data to be filtered is that the name cannot be duplicated?
table = dv.ToTable(true, new string[] { "name"});
Get:
Name zhang San Li Si
However, the result I want is to repeat only one column of name and display other columns.
The result is:
Id name code1 Zhang San 1232 Li Si 456
How can this be achieved? The following method is acceptable. There may be better methods. I hope you will give me more advice.
1 # region Delete the repeated columns of the DataTable, similar to distinct 2 // <summary> 3 // Delete the repeated columns of the DataTable, similar to distinct 4 /// </summary> 5 /// <param name = "dt"> DataTable </param> 6 /// <param name = "Field"> Field name </param> 7 // <returns> </returns> 8 public static DataTable DeleteSameRow (DataTable dt, string Field) 9 {10 ArrayList indexList = new ArrayList (); 11 // locate the row index to be deleted 12 for (int I = 0; I <dt. rows. count-1; I ++) 13 {14 if (! IsContain (indexList, I) 15 {16 for (int j = I + 1; j <dt. rows. count; j ++) 17 {18 if (dt. rows [I] [Field]. toString () = dt. rows [j] [Field]. toString () 19 {20 indexList. add (j); 21} 22} 23} 24} 25 indexList. sort ();
// Sort 26 for (int I = indexList. count-1; I> = 0; I --) // Delete the Row 27 {28 int index = Convert according to the index list to be deleted. toInt32 (indexList [I]); 29 dt. rows. removeAt (index); 30} 31 return dt; 32} 33 34 // <summary> 35 // determine whether the array contains 36 /// </summary> 37 /// <param name = "indexList"> Array </param> 38 // <param name = "index"> index </param> 39 // <returns> </returns> 40 public static bool IsContain (ArrayList indexList, int index) 41 {42 for (int I = 0; I <indexList. count; I ++) 43 {44 int tempIndex = Convert. toInt32 (indexList [I]); 45 if (tempIndex = index) 46 {47 return true; 48} 49} 50 return false; 51} 52 # endregion