过滤某列的值重复的行?

love22 2004-09-02 09:33:15
DataTable中怎样过滤某列的值重复的行?
...全文
100 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
love22 2004-09-02
  • 打赏
  • 举报
回复
谢谢楼上
zhjboss 2004-09-02
  • 打赏
  • 举报
回复
DataTable t = new DataTable();
t.Columns.Add("Name", typeof(string));
DataRow row = t.NewRow();
row["Name"] = "a";
t.Rows.Add(row);
row = t.NewRow();
row["Name"] = "a";
t.Rows.Add(row);
怎样过滤重复的行?
/// <summary>
// 过滤DataTable中重复的行,如果这些行的某列是相等的
/// </summary>
/// <param name="SourceTable">源表</param>
/// <param name="FieldName">列名</param>
/// <returns></returns>
public DataTable SelectDistinct(DataTable table, string FieldName)
{
DataRow[] drs = table.Select("", FieldName);
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 table;
}

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
}

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧