#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)
{
//弊端是多了数据中多了一个空格也视为不同
//DataView dv = dt.DefaultView;
//string[] paras = new string[dt.Columns.Count];
//for (int i = 0; i < dt.Columns.Count; i++)
//{
// paras[i] = dt.Columns[i].ToString();
//}
//DataTable dtDistinct = dv.ToTable(true, paras);
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);
}
}
}
}
// 根据待删除索引列表删除行--删除的过程中索引号不断的变化--错误不可使用
//int count = 0;
//for (int i = indexList.Count - 1; i >= 0; i--)
//{
// int index = Convert.ToInt32(indexList[i]);
// dt.Rows.RemoveAt(index - count);
// count++;
//}
DataTable dtNew = dt.Clone();
dtNew.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (!IsContain(indexList, i))
{
dtNew.ImportRow(dt.Rows[i]);
}
else
{
int a = i;
}
}
return dtNew;
}