刪除DataTable重復列,只針對刪除其中的一列重復的行


vs2005針對datatable已經有封裝好的去重復方法:

1 //去掉重復行
2 DataView dv = table.DefaultView;
3 table = dv.ToTable(true, new string[] { "name", "code" });
4 
5 此時table 就只有name、code無重復的兩行了,如果還需要id值則
6 
7 table = dv.ToTable(true, new string[] { "id","name", "code" });//第一個參數true 啟用去重復,類似distinct

如果有一組數據(id不是唯一字段)

 

id   name   code


1    張三    123

2    李四    456

3    張三    456

1   張三     123

 

通過上面的方法得到

 id   name   code


1    張三    123

2    李四    456

3    張三    456

 

去重復去掉的僅僅是 id name code完全重復的行,如果想要篩選的數據僅僅是name不允許重復呢?

table = dv.ToTable(true, new string[] { "name"});

得到:

name 
 
張三  
  
李四  

但是我想要的結果是只針對其中的一列name列 去重復,還要顯示其他的列

需要的結果是:

 id   name   code


1    張三    123

2    李四    456

這個該怎么實現?下面的方法就可以,也許有更好的方法,希望大家多多指教

 1  #region 刪除DataTable重復列,類似distinct
 2         /// <summary>   
 3         /// 刪除DataTable重復列,類似distinct   
 4         /// </summary>   
 5         /// <param name="dt">DataTable</param>   
 6         /// <param name="Field">字段名</param>   
 7         /// <returns></returns>   
 8         public static DataTable DeleteSameRow(DataTable dt, string Field)
 9         {
10             ArrayList indexList = new ArrayList();
11             // 找出待刪除的行索引   
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();
 // 排序
26 for (int i = indexList.Count - 1; i >= 0; i--)// 根據待刪除索引列表刪除行  27 { 28 int index = Convert.ToInt32(indexList[i]); 29 dt.Rows.RemoveAt(index); 30 } 31 return dt; 32 } 33 34 /// <summary> 35 /// 判斷數組中是否存在 36 /// </summary> 37 /// <param name="indexList">數組</param> 38 /// <param name="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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM