C#讀取數(shù)據(jù)庫返回泛型集合詳解(DataSetToList)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
IList<LYZX.Model.LYZX_NewsTypeModel> list = GetList<LYZX.Model.LYZX_NewsTypeModel>(System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString,
"select * from LYZX_NewsType");
GridView1.DataSource = list;
GridView1.DataBind();
}
}
public string GetNewsTypeLink(ref string baseUrl,Guid newsType)
{
return "";
}
/// <summary>
/// 獲取泛型集合
/// /// </summary>
/// /// <typeparam name="T">類型</typeparam>
/// /// <param name="connStr">數(shù)據(jù)庫連接字符串</param>
/// <param name="sqlStr">要查詢的T-SQL</param>
/// <returns></returns>
public IList<T> GetList<T>(string connStr, string sqlStr)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, conn))
{
DataSet ds = new DataSet();
sda.Fill(ds);
return DataSetToList<T>(ds, 0);
}
}
}
/// <summary>
/// DataSetToList
/// </summary>
/// <typeparam name="T">轉換類型</typeparam>
/// <param name="dataSet">數(shù)據(jù)源</param>
/// <param name="tableIndex">需要轉換表的索引</param>
/// /// <returns>泛型集合</returns>
public IList<T> DataSetToList<T>(DataSet dataset,int tableIndex)
{
//確認參數(shù)有效
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++)
{
//創(chuàng)建泛型對象
T _t=Activator.CreateInstance<T>();
//獲取對象所有屬性
PropertyInfo [] propertyInfo=_t.GetType().GetProperties();
//屬性和名稱相同時則賦值
for (int j = 0; j < dt.Columns.Count; j++)
{
foreach (PropertyInfo info in propertyInfo)
{
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;
}
相關文章
C#中Arraylist的sort函數(shù)用法實例分析
這篇文章主要介紹了C#中Arraylist的sort函數(shù)用法,較為詳細的分析了ArrayList的sort函數(shù)的功能、定義及具體使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10
c#使用IAsyncEnumerable實現(xiàn)流式分段傳輸
這篇文章主要為大家詳細介紹了c#如何使用IAsyncEnumerable實現(xiàn)流式分段傳輸,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-10-10
巧用Dictionary實現(xiàn)日志數(shù)據(jù)批量插入
這篇文章主要介紹了巧用Dictionary實現(xiàn)日志數(shù)據(jù)批量插入,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02

