[C#] DataTable轉成List集合

項目開發中,常常會獲取到DataTable對象,如何把它轉化成一個List對象呢?前幾天就碰到這個問題,網上搜索整理了一個萬能類,用了泛型和反射的知識。共享以下:spa

 

public class ModelConvertHelper<T> where T : new()  // 此處必定要加上new()
    {

        public static IList<T> ConvertToModel(DataTable dt)
        {

            IList<T> ts = new List<T>();// 定義集合
            Type type = typeof(T); // 得到此模型的類型
            string tempName = "";
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T(); 
                PropertyInfo[] propertys = t.GetType().GetProperties();// 得到此模型的公共屬性
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pi.CanWrite) continue;
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
    }
相關文章
相關標籤/搜索