List对象转换成DataTable在linq当中很使用

List<>对象转换成dataTable
private DataTable changeDataTable(object lst模块)
        {
            DataTable dt = new DataTable();
            IList list = (IList)lst模块;

            // 通过使用反射来获取列表中队形的属性

            BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty;
            PropertyInfo[] props = list[0].GetType().GetProperties();
            foreach (PropertyInfo pi in props)
                dt.Columns.Add(pi.Name,Type.GetType(pi.PropertyType.FullName));

            foreach (object obj in list)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in props)
                {
                    object result = obj.GetType().InvokeMember(pi.Name, bf, null, obj, null);
                   // d.Add(result);
                    dr[pi.Name] = result;  
                }
               dt.Rows.Add(dr);
            }
            return dt;
        }

posted on 2010-12-22 11:07  guoxuefeng  阅读(919)  评论(0编辑  收藏  举报