我知道這個問題很老,但它可能會幫助有人想要這樣做。
創建來自動態對象的DataTable和數據表結合的GridView
public static DataTable GetDataTableFromDynamicObject (List<dynamic> listData)
{
DataTable table = new DataTable ();
if (listData.Count > 0)
{
var firstRow = (IEnumerable<KeyValuePair<string, JToken>>) (JObject) listData.First ();
foreach (KeyValuePair<string, JToken> property in firstRow.OrderBy (x => x.Key))
table.Columns.Add (new DataColumn (property.Key));
foreach (var data in listData)
{
DataRow row = table.NewRow ();
var record = (IEnumerable<KeyValuePair<string, JToken>>) (JObject) data;
foreach (KeyValuePair<string, JToken> kvp in record)
{
row [ kvp.Key ] = kvp.Value;
}
table.Rows.Add (row);
}
}
return table;
}