DataTable 轉集合

 /// <summary>
    /// DataTable轉換爲List<Model>;
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class DataTableToListModel<T> where T : new()
    {
        public static IList<T> ConvertToModel(DataTable dt)
        {
            //定義集合
            List<T> ts = new List<T>();
            string tempName = "";
            T t = new T();
            PropertyInfo[] propertys = t.GetType().GetProperties();
            foreach (DataRow row in dt.Rows)
            {
                t = new T();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pi.CanWrite)
                            continue;
                        object value = row[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

    }

public class user {
        private int id;
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

//調用:

List<user> ilist=  Web.DataTableToListModel<user>.ConvertToModel(dt);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章