C# convert json to datatable,convert list to datatable

1 static DataTable ConvertJsonToTable(string jsonValue)
2         {
3             DataTable dt = (DataTable)JsonConvert.DeserializeObject(jsonValue, typeof(DataTable));             
4             return dt;          
5         }
static DataTable ConvertListToDataTable<T>(List<T> dataList)
        {
            DataTable dt = new DataTable();
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            for(int i=0;i<props.Count;i++)
            {
                PropertyDescriptor prop = props[i];
                dt.Columns.Add(prop.Name, prop.PropertyType);
            }
            object[] values = new object[props.Count];
            foreach(T item in dataList)
            {
                for(int i=0;i<values.Length;i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                dt.Rows.Add(values);
            }
            return dt;
        }
 static DataTable ConvertTToDT<T>(List<T> dataList)
        {
            if(dataList==null || !dataList.Any())
            {
                return null;
            }

            DataTable dt = new DataTable();
            PropertyInfo[] pis = typeof(T).GetProperties();
            for(int i=0;i<pis.Count();i++)
            {
                dt.Columns.Add(pis[i].Name, pis[i].PropertyType);
            }

            object[] valuesArr = new object[pis.Count()];
            foreach(var data in dataList)
            {
                for(int i=0;i<pis.Count();i++)
                {
                    valuesArr[i] = pis[i].GetValue(data);
                }
                dt.Rows.Add(valuesArr);
            }             
            return dt;
        }
posted @ 2020-04-22 15:21  额头有王的喵  阅读(107)  评论(0编辑  收藏