获取DataTable字段唯一值(DISTINCT)
/// <summary>
/// 将所选字段的唯一值复制到一个新的 DataTable。
/// <para>如果字段包含 NULL 值,目标表中的记录还包含 NULL 值</para>
/// </summary>
/// <param name="sourceTable">源数据表</param>
/// <param name="filterExpression">检索条件</param>
/// <param name="fieldName">唯一值的字段名</param>
/// <returns></returns>
public DataTable SelectDistinct(DataTable sourceTable, string filterExpression, string fieldName)
{
DataTable dt = new DataTable(sourceTable.TableName);
dt.Columns.Add(fieldName, sourceTable.Columns[fieldName].DataType);
object lastValue = null;
foreach (DataRow dr in sourceTable.Select(filterExpression, fieldName))
{
if (lastValue == null || !(ColumnEqual(lastValue, dr[fieldName])))
{
lastValue = dr[fieldName];
dt.Rows.Add(new object[] { lastValue });
}
}
return dt;
}
private 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));
}
/// 将所选字段的唯一值复制到一个新的 DataTable。
/// <para>如果字段包含 NULL 值,目标表中的记录还包含 NULL 值</para>
/// </summary>
/// <param name="sourceTable">源数据表</param>
/// <param name="filterExpression">检索条件</param>
/// <param name="fieldName">唯一值的字段名</param>
/// <returns></returns>
public DataTable SelectDistinct(DataTable sourceTable, string filterExpression, string fieldName)
{
DataTable dt = new DataTable(sourceTable.TableName);
dt.Columns.Add(fieldName, sourceTable.Columns[fieldName].DataType);
object lastValue = null;
foreach (DataRow dr in sourceTable.Select(filterExpression, fieldName))
{
if (lastValue == null || !(ColumnEqual(lastValue, dr[fieldName])))
{
lastValue = dr[fieldName];
dt.Rows.Add(new object[] { lastValue });
}
}
return dt;
}
private 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));
}