Convert ExpandoObject to DataTable

Snippet
/// <summary>
/// Create a datatable from a list of ExpandoObjects
/// </summary>
/// <param name="list">The list can be created from a dictionary with Dictionary.Values.ToList()</param>
/// <param name="tableName">Name of the data table</param>
/// <returns></returns>
public static DataTable ToDataTable(this List<ExpandoObject> list, string tableName)
{
	if (list == null || list.Count == 0) return null;
	//build columns
	var props = (IDictionary<string, object>)list[0];
	var t = new DataTable(tableName);
	foreach (var prop in props)
	{
		t.Columns.Add(new DataColumn(prop.Key, prop.Value.GetType()));
	}
	//add rows
	foreach (var row in list)
	{
		var data = t.NewRow();
		foreach (var prop in (IDictionary<string, object>)row)
		{
			data[prop.Key] = prop.Value;
		}
		t.Rows.Add(data);
	}
	return t;
}

One Response to “Convert ExpandoObject to DataTable”

  1. XelaNimed says:

    Thank you so much!
    I searched for this solution for a long time.

Leave a Reply

Your email address will not be published. Required fields are marked *