Convert ExpandoObject to DataTable

/// <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;
	return t;

2 Responses to “Convert ExpandoObject to DataTable”

  1. XelaNimed says:

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

  2. Helmi says:

    Thanks a lot, that’s a life saver!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.