最近做一个把源数据库的数据批次导出到目标数据库。源数据库是采集程序采集而来的原始数据库,所以需要对其进行一些处理(过滤一些为空,长度太短或太长,非法字符,重复数据)然后在进行入库。
public static DataTable Distinct(DataTable dt, string[] filedNames)
{
DataView dv = dt.DefaultView;
DataTable DistTable = dv.ToTable("Dist", true, filedNames);
return DistTable;
}
利用for循环遍历DataTable的数据行,利用DataTable.Select 方法判断是否重复,如果重复,则利用DataTable.Rows.RemoveAt(Index)删除重复的那一行。
public DataTable GetDistinctSelf(DataTable SourceDt, string filedName)
{
for (int i = SourceDt.Rows.Count - 2; i > 0; i--)
{
DataRow[] rows = SourceDt.Select(string.Format("{0}=‘{1}‘", filedName, SourceDt.Rows[i][filedName]));
if (rows.Length > 1)
{
SourceDt.Rows.RemoveAt(i);
}
}
return SourceDt;
}
public DataTable GetDistinctSelf(DataTable SourceDt, string filedName)
{
for (int i = SourceDt.Rows.Count - 2; i > 0; i--)
{
string title = SourceDt.Rows[0][filedName].ToString();
for (int j = i + 1; j > 0; i--)
{
if (SourceDt.Rows[j][filedName].ToString() == title)
{
SourceDt.Rows.RemoveAt(i);
}
}
}
return SourceDt;
}