Define a class:
public class UserInfo
{
Public System.Guid ID {get; set;}
public string LoginName {get; set;}
public string Loginpwd {get; set;}
}
<summary>
Get UserInfo Generic Collection
</summary>
<param name= "CONNSTR" > Database connection string </param>
<param name= "Sqlstr" > t-sql</param> to Query
<returns></returns>
Public ilist<userinfo> Getuserinfoall (string connstr, String sqlstr)
{
using (SqlConnection conn = new SqlConnection (CONNSTR))
{
using (SqlCommand cmd = new SqlCommand (SQLSTR, conn))
{
SqlDataReader SDR = cmd. ExecuteReader ();
ilist<userinfo> list = new list<userinfo> ();
while (SDR. Read ())
{
UserInfo UserInfo = new UserInfo ();
Userinfo.id = (Guid) sdr["ID"];
Userinfo.loginname = sdr["LoginName"]. ToString ();
Userinfo.loginpwd = sdr["Loginpwd"]. ToString ();
List. ADD (UserInfo);
}
return list;
}
}
}
//<summary>
//Get generic collection
//</summary>
//<typeparam name= "T" > Type </typeparam>< br>//<param name= "CONNSTR" > Database connection string </param>
//<param name= "Sqlstr" > T-sql</param to Query
//<returns></returns>
Public ilist<t> getlist<t> (string connstr, String sqlstr)
{
using (SqlConnection conn = new SqlConnection (connstr))
{
using (SqlDataAdapter SDA = new Sqldataadapte R (SQLSTR, conn))
{
DataSet ds = new DataSet ();
SDA. Fill (DS);
Return datasettolist<t> (ds, 0);
}
}
}
<summary>
Datasettolist
</summary>
<typeparam name= "T" > Conversion type </typeparam>
<param name= "DataSet" > Data source </param>
<param name= "Tableindex" > Need to convert table index </param>
<returns></returns>
Public ilist<t> datasettolist<t> (DataSet DataSet, int tableindex)
{
Verify that the parameters are valid
if (DataSet = = NULL | | DataSet.Tables.Count <= 0 | | Tableindex < 0)
return null;
DataTable dt = Dataset.tables[tableindex];
ilist<t> list = new list<t> ();
for (int i = 0; i < dt. Rows.Count; i++)
{
Creating generic objects
T _t = activator.createinstance<t> ();
Get all properties of an object
propertyinfo[] PropertyInfo = _t.gettype (). GetProperties ();
for (int j = 0; j < dt. Columns.count; J + +)
{
foreach (PropertyInfo info in PropertyInfo)
{
Property name and column name are both assigned values
if (dt. COLUMNS[J]. Columnname.toupper (). Equals (info. Name.toupper ()))
{
if (dt. ROWS[I][J]! = DBNull.Value)
{
Info. SetValue (_t, dt. ROWS[I][J], NULL);
}
Else
{
Info. SetValue (_t, NULL, NULL);
}
Break
}
}
}
List. ADD (_t);
}
return list;
}
Generics learning the third day--c# read the database returns a generic collection converts a dataset type to a list<t> generic collection