C#将DataTable 转化为List<T> 扩展方法

最近学习的C#的高级特性,将普通方法转化为扩展方法
扩展方法必须为静态方法切需要放在静态类中

public static List<T> ToList<T>(this DataTable dt)
{
    //调用方式为  List<T> dtlist=  dt.ToList<T>(); 




    List<T> ts = new List<T>(); 
    Type type = typeof(T);
    string tempName = "";

    foreach (DataRow dr in dt.Rows)
     {
        T t = (T)Activator.CreateInstance(type);     
        PropertyInfo[] propertys = t.GetType().GetProperties();
        foreach (PropertyInfo pi in propertys)
        {
            tempName = pi.Name;    

            if (dt.Columns.Contains(tempName))
            { 
                if (!pi.CanWrite) continue;

                var value = dr[tempName].ToString();
                if (!string.IsNullOrEmpty(value))
                    pi.SetValue(t, value, null);
            }
        }
        ts.Add(t);
    }
    return ts;
}
posted @ 2021-06-02 15:11  醒来才知是梦  阅读(160)  评论(0)    收藏  举报