[转]过滤datatable中重复的字段
思路就是先给dt排序,然后只要相邻的两个逐个对比就可以了
Code
过滤DataTable中的指定字段重复的行收藏
过滤DataTable中的指定字段重复的行#region 过滤DataTable中的指定字段重复的行
/**//**//**//// <summary>
/// 过滤DataTable中的指定字段重复的行
/// </summary>
/// <param name="dt"></param>
/// <param name="FieldName"></param>
/// <returns></returns>
public DataTable SelectDistinctByField(DataTable dt, string FieldName)
{
DataTable returnDt = new DataTable();
returnDt = dt.Copy();//将原DataTable复制一个新的
DataRow[] drs = returnDt.Select("", FieldName);//将DataTable按指定的字段排序
object LastValue = null;
for (int i = 0; i < drs.Length; i++)
{
if ((LastValue == null) || (!(ColumnEqual(LastValue, drs[i][FieldName]))))
{
LastValue = drs[i][FieldName];
continue;
}
drs[i].Delete();
}
return returnDt;
}
private bool ColumnEqual(object A, object B)
{
// Compares two values to see if they are equal. Also compares DBNULL.Value.
// Note: If your DataTable contains object fields, then you must extend this
// function to handle them in a meaningful way if you intend to group on them.
if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
return true;
if (A == DBNull.Value || B == DBNull.Value) // only one is DBNull.Value
return false;
return (A.Equals(B)); // value type standard comparison
}
#endregion
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lxy_abcde1190/archive/2008/05/25/2479386.aspx
过滤DataTable中的指定字段重复的行收藏
过滤DataTable中的指定字段重复的行#region 过滤DataTable中的指定字段重复的行
/**//**//**//// <summary>
/// 过滤DataTable中的指定字段重复的行
/// </summary>
/// <param name="dt"></param>
/// <param name="FieldName"></param>
/// <returns></returns>
public DataTable SelectDistinctByField(DataTable dt, string FieldName)
{
DataTable returnDt = new DataTable();
returnDt = dt.Copy();//将原DataTable复制一个新的
DataRow[] drs = returnDt.Select("", FieldName);//将DataTable按指定的字段排序
object LastValue = null;
for (int i = 0; i < drs.Length; i++)
{
if ((LastValue == null) || (!(ColumnEqual(LastValue, drs[i][FieldName]))))
{
LastValue = drs[i][FieldName];
continue;
}
drs[i].Delete();
}
return returnDt;
}
private bool ColumnEqual(object A, object B)
{
// Compares two values to see if they are equal. Also compares DBNULL.Value.
// Note: If your DataTable contains object fields, then you must extend this
// function to handle them in a meaningful way if you intend to group on them.
if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
return true;
if (A == DBNull.Value || B == DBNull.Value) // only one is DBNull.Value
return false;
return (A.Equals(B)); // value type standard comparison
}
#endregion
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lxy_abcde1190/archive/2008/05/25/2479386.aspx