Transfer from http://www.cnblogs.com/wuhuisheng/archive/2012/04/26/2471733.html
1 /// <summary>2 ///get userinfo Generic collection3 /// </summary>4 /// <param name= "ConnStr" >Database connection String</param>5 /// <param name= "Sqlstr" >T-SQL to query</param>6 /// <returns></returns>7 PublicIlist<userinfo> Getuserinfoall (stringConnStr,stringsqlstr)8 {9 using(SqlConnection conn =NewSqlConnection (connstr))Ten { One using(SqlCommand cmd =NewSqlCommand (SQLSTR, conn)) A { -SqlDataReader SDR =cmd. ExecuteReader (); - theilist<userinfo> list =NewList<userinfo>(); - - while(SDR). Read ()) - { + -UserInfo UserInfo =NewUserInfo (); + AUserinfo.id = (Guid) sdr["ID"]; at -Userinfo.loginname = sdr["LoginName"]. ToString (); - -Userinfo.loginpwd = sdr["loginpwd"]. ToString (); - - list. ADD (userInfo); in - } to returnlist; + } - } the } * $ /// <summary>Panax Notoginseng ///Get generic collection - /// </summary> the /// <typeparam name= "T" >type</typeparam> + /// <param name= "ConnStr" >Database connection String</param> A /// <param name= "Sqlstr" >T-SQL to query</param> the /// <returns></returns> + PublicIlist<t> getlist<t> (stringConnStr,stringsqlstr) - { $ using(SqlConnection conn =NewSqlConnection (connstr)) $ { - using(SqlDataAdapter SDA =NewSqlDataAdapter (SQLSTR, conn)) - { theDataSet ds =NewDataSet (); - SDA. Fill (DS);Wuyi returnDatasettolist<t> (DS,0); the } - } Wu } - About /// <summary> $ ///datasettolist - /// </summary> - /// <typeparam name= "T" >Conversion Type</typeparam> - /// <param name= "DataSet" >Data Source</param> A /// <param name= "Tableindex" >indexes that need to convert tables</param> + /// <returns></returns> the PublicIlist<t> datasettolist<t> (DataSet DataSet,intTableindex) - { $ //Verify that the parameters are valid the if(DataSet = =NULL|| DataSet.Tables.Count <=0|| Tableindex <0) the return NULL; the theDataTable dt =Dataset.tables[tableindex]; - inilist<t> list =NewList<t>(); the the for(inti =0; i < dt. Rows.Count; i++) About { the //Creating generic Objects theT _t = activator.createinstance<t>(); the //get all Properties of an object +propertyinfo[] PropertyInfo =_t.gettype (). GetProperties (); - for(intj =0; J < dt. Columns.count; J + +) the {Bayi foreach(PropertyInfo InfoinchpropertyInfo) the { the //property name and column name are both assigned values - if(dt. COLUMNS[J]. Columnname.toupper (). Equals (info. Name.toupper ())) - { the if(dt. ROWS[I][J]! =DBNull.Value) the { theInfo. SetValue (_t, dt. ROWS[I][J],NULL); the } - Else the { theInfo. SetValue (_t,NULL,NULL); the }94 Break; the } the } the }98 list. ADD (_t); About } - returnlist;101}
public class UserInfo
{
Public System.Guid ID {get; set;}
public string LoginName {get; set;}
public string Loginpwd {get; set;}
}
Read database return generic collection convert dataset type to list<t> generic collection