不说废话,直接看代码吧
public static DataTable SelectDistinct(DataTable SourceTable, string keyFields)
{
if (SourceTable == null)
return null;
DataTable dtRet = SourceTable.Clone();//定义返回记录表
//获得参照列列表
string[] sFields = keyFields.Split(',');//获得参照列列表
if (sFields.Length == 0)
return SourceTable;
DataRow[] dr = SourceTable.Select("", keyFields);//按参照列排序
if (dr.Length == 0)
return SourceTable;
DataRow lastRow = dtRet.NewRow();//定义对照值
foreach (DataRow row in dr)//开始比对
{
//定义列比对结果
int result = 0;
object oSrc;
object oDest;
//循环比对列值
for (int colIndex = 0; colIndex < sFields.Length; colIndex++)
{
//获得列值
oSrc = row[sFields[colIndex]];
oDest = lastRow[sFields[colIndex]];
//比较列值,不相等则退出循环
if (oSrc == DBNull.Value)
{
result = oDest == DBNull.Value ? 0 : -1;
}
else
{
result = oDest == DBNull.Value ? 1 : string.Compare(oSrc.ToString(), oDest.ToString(), false);
}
if (result != 0)
break;
}
//检查行比较结果
switch (result)
{
case 0://相同则放弃
break;
case -1://不同则加入,并将当前比较字符串赋给对照值
case 1:
dtRet.Rows.Add(row.ItemArray);
lastRow = row;
break;
default:
break;
}
}
return dtRet;
}
思路:对记录进行前后循环比对,保留不一致的。