ADO.NET 从DataTable中获取某列含有的不同值的几种方式
在实际开发过程中也许不少人也遇到过我同样的需求:
需要获取DataTable中某一列或几列的含有的不同值,得到类似SQL中Group By的结果
1、传统做法是遍历DataTable(.NET Framework个版本通用)
/// 按照fieldName从sourceTable中选择出不重复的行,
/// 相当于select distinct fieldName1,fieldName2,,fieldNamen from sourceTable
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="sourceTable">源DataTable</param>
/// <param name="fieldNames">列名数组</param>
/// <returns>一个新的不含重复行的DataTable,列只包括fieldNames中指明的列</returns>
public DataTable SelectDistinct(string tableName, DataTable sourceTable, string[] fieldNames)
{
DataTable dt = new DataTable( tableName );
object[] values = new object[fieldNames.Length];
string fields = "";
for ( int i = 0; i < fieldNames.Length; i++ )
{
dt.Columns.Add( fieldNames[ i ], sourceTable.Columns[ fieldNames[ i ] ].DataType );
fields += fieldNames[ i ] + ",";
}
fields = fields.Remove( fields.Length - 1, 1 );
DataRow lastRow = null;
foreach ( DataRow dr in sourceTable.Select( "", fields ) )
{
if ( lastRow == null || !( RowEqual( lastRow, dr, dt.Columns ) ) )
{
lastRow = dr;
for ( int i = 0; i < fieldNames.Length; i++ )
{
values[ i ] = dr[ fieldNames[ i ] ];
}
dt.Rows.Add( values );
}
}
if ( ds != null && !ds.Tables.Contains( tableName ) )
{
ds.Tables.Add( dt );
}
return dt;
/// 相当于select distinct fieldName1,fieldName2,,fieldNamen from sourceTable
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="sourceTable">源DataTable</param>
/// <param name="fieldNames">列名数组</param>
/// <returns>一个新的不含重复行的DataTable,列只包括fieldNames中指明的列</returns>
public DataTable SelectDistinct(string tableName, DataTable sourceTable, string[] fieldNames)
{
DataTable dt = new DataTable( tableName );
object[] values = new object[fieldNames.Length];
string fields = "";
for ( int i = 0; i < fieldNames.Length; i++ )
{
dt.Columns.Add( fieldNames[ i ], sourceTable.Columns[ fieldNames[ i ] ].DataType );
fields += fieldNames[ i ] + ",";
}
fields = fields.Remove( fields.Length - 1, 1 );
DataRow lastRow = null;
foreach ( DataRow dr in sourceTable.Select( "", fields ) )
{
if ( lastRow == null || !( RowEqual( lastRow, dr, dt.Columns ) ) )
{
lastRow = dr;
for ( int i = 0; i < fieldNames.Length; i++ )
{
values[ i ] = dr[ fieldNames[ i ] ];
}
dt.Rows.Add( values );
}
}
if ( ds != null && !ds.Tables.Contains( tableName ) )
{
ds.Tables.Add( dt );
}
return dt;
}
2、简单代码实现方式(只适用于.NET Framework2.0及以后版本)
DataTable SourceTable = new SourseTable();
SourceTable.Columns.Add("Code",string);
//...向SourseTable中添加数据
DataView view = new DataView(SourceTable);
string[] columns = {"Code"}
SourceTable.Columns.Add("Code",string);
//...向SourseTable中添加数据
DataView view = new DataView(SourceTable);
string[] columns = {"Code"}
DataTable tarTable = view.ToTable(true,columns);//得到目标
3、使用Linq to Sql(只适用于.NET Framework3.5及以后版本)
用发现的眼光来看这个互联网,总有我们立脚的地方!——北纬28.33