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
}
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
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货