I have a dynamic list in the below format and wanted to convert into a datatable.
The reason behind dynamic is the columns will keep varying based in this input.
Input:
{{
"EMP_ID": "12345",
"Client": "abcdef",
"Business_Type": "Temping",
"EMP NO": "098765",
"Associate Id": "mki0987"
}}
The above list is generated from a json string
{[ {
"EMP_ID": "12345",
"Client": "abcdef",
"Business_Type": "Temping",
"EMP NO": "098765",
"Associate Id": "mki0987"
}]}
Expected Output:
EMP_ID | Client | Business_Type | EMP NO | Associate ID
--------|---------|-----------------|----------|-------------------
12345 | abcdef | Temping | 098765 | mki0987
--------|---------|-----------------|----------|-------------------
Any ideas to achieve this.
I tried doing this using reflection as mentioned below
public static DataTable ToDataTable<T>(List<T> items) {
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties();
foreach (PropertyInfo prop in Props) {
//Defining type of data column gives proper data table
//var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items) {
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++) {
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
But in this particular code Get properties is not returning me anything as column names