//去掉重復行
DataView dv = table.DefaultView; table = dv.ToTable(true, new string[] { "name", "code" }); 此時table 就只有name、code無重復的兩行了,如果還需要id值則 table = dv.ToTable(true, new string[] { "id","name", "code" });//第一個參數true 啟用去重復,類似distinct
如果有一組數據(id不是唯一字段)
通過上面的方法得到
去重復去掉的僅僅是 id name code完全重復的行,如果想要篩選的數據僅僅是name不允許重復呢?
table = dv.ToTable(true, new string[] { "name"});
得到:
但是我想要的結果是只針對其中的一列name列 去重復,還要顯示其他的列
需要的結果是:
該怎么實現?下面的方法就可以,也許有更好的方法,
#region 刪除DataTable重復列,類似distinct
/// <summary>
/// 刪除DataTable重復列,類似distinct /// </summary>
/// <param name="dt">DataTable</param>
/// <param name="Field">字段名</param>
/// <returns></returns>
public static DataTable DeleteSameRow(DataTable dt, string Field) { ArrayList indexList = new ArrayList(); // 找出待刪除的行索引
for (int i = 0; i < dt.Rows.Count - 1; i++) { if (!IsContain(indexList, i)) { for (int j = i + 1; j < dt.Rows.Count; j++) { if (dt.Rows[i][Field].ToString() == dt.Rows[j][Field].ToString()) { indexList.Add(j); } } } } indexList.Sort(); // 排序
for (int i = indexList.Count - 1; i >= 0; i--)// 根據待刪除索引列表刪除行
{ int index = Convert.ToInt32(indexList[i]); dt.Rows.RemoveAt(index); } return dt; } /// <summary>
/// 判斷數組中是否存在 /// </summary>
/// <param name="indexList">數組</param>
/// <param name="index">索引</param>
/// <returns></returns>
public static bool IsContain(ArrayList indexList, int index) { for (int i = 0; i < indexList.Count; i++) { int tempIndex = Convert.ToInt32(indexList[i]); if (tempIndex == index) { return true; } } return false; } #endregion
原文:https://blog.csdn.net/qq_23502409/article/details/75269221