当你有一天你厌烦了访问数据库
这时候你也许会碰到以前没有的问题
你获得的DataTable中有重复的数据
于是
public class DataSetHelper
{
public DataSet ds;
public DataSetHelper(ref DataSet DataSet)
{
ds = DataSet;
}
public DataSetHelper()
{
ds = null;
}
private static bool ColumnEqual(object A, object B)
{
if (A == DBNull.Value && B == DBNull.Value)
return true;
if (A == DBNull.Value || B == DBNull.Value)
return false;
return (A.Equals(B));
}
//新表名,原表,作用的字段名 返回新表
public static DataTable SelectDistinct(string TableName, DataTable SourceTable, string FieldName)
{
DataTable dt = new DataTable(TableName);
dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);
object LastValue = null;
foreach (DataRow dr in SourceTable.Select("", FieldName))
{
if (LastValue == null || !(ColumnEqual(LastValue, dr[FieldName])))
{
LastValue = dr[FieldName];
dt.Rows.Add(new object[] { LastValue });
}
}
if (ds != null)
ds.Tables.Add(dt);
return dt;
}
}
这时候你也许会碰到以前没有的问题
你获得的DataTable中有重复的数据
于是
public class DataSetHelper
{
public DataSet ds;
public DataSetHelper(ref DataSet DataSet)
{
ds = DataSet;
}
public DataSetHelper()
{
ds = null;
}
private static bool ColumnEqual(object A, object B)
{
if (A == DBNull.Value && B == DBNull.Value)
return true;
if (A == DBNull.Value || B == DBNull.Value)
return false;
return (A.Equals(B));
}
//新表名,原表,作用的字段名 返回新表
public static DataTable SelectDistinct(string TableName, DataTable SourceTable, string FieldName)
{
DataTable dt = new DataTable(TableName);
dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);
object LastValue = null;
foreach (DataRow dr in SourceTable.Select("", FieldName))
{
if (LastValue == null || !(ColumnEqual(LastValue, dr[FieldName])))
{
LastValue = dr[FieldName];
dt.Rows.Add(new object[] { LastValue });
}
}
if (ds != null)
ds.Tables.Add(dt);
return dt;
}
}