ExpandoObject到DataTable

时间:2014-12-05 16:27:51

标签: c# datatable converter expandoobject

我是新的ExpandoObject(事实上,我昨天发现了它)。我有以下代码,并想知道是否有某种方法将ExpandoObject转换为我不知道的DataTable?或者我必须使用反射来自己转换它?

dynamic contacts = new List<dynamic>();

contacts.Add(new ExpandoObject());
contacts[0].Name = "Patrick Hines";
contacts[0].Phone = "206-555-0144";

contacts.Add(new ExpandoObject());
contacts[1].Name = "Ellen Adams";
contacts[1].Phone = "206-555-0155";

2 个答案:

答案 0 :(得分:2)

以下是我要转换的内容。但如果有人有更好的方法,请告诉我。

    public DataTable ToDataTable(IEnumerable<dynamic> items)
    {
        var data = items.ToArray();
        if (data.Count() == 0) return null;

        var dt = new DataTable();
        foreach (var key in ((IDictionary<string, object>)data[0]).Keys)
        {
            dt.Columns.Add(key);
        }
        foreach (var d in data)
        {
            dt.Rows.Add(((IDictionary<string, object>)d).Values.ToArray());
        }
        return dt;
    }

答案 1 :(得分:0)

您可以使用此代码。 Linq会帮助你:)

var contacts = new List<dynamic>();

contacts.Add(new ExpandoObject());
contacts[0].Name = "Patrick Hines";
contacts[0].Phone = "206-555-0144";

contacts.Add(new ExpandoObject());
contacts[1].Name = "Ellen Adams";
contacts[1].Phone = "206-555-0155";
// DataTable Instance...
DataTable table = new DataTable();

//Get all properties of contract list items
var properties = contacts.GetType().GetProperties();

// Remove contract list property
properties = properties.ToList().GetRange(0, properties.Count() - 1).ToArray();

// Add column as named by property name
properties.ToList().ForEach(p => table.Columns.Add(p.Name,typeof(string)));

// Add rows from contracts list
contacts.ForEach(x =>  table.Rows.Add(x.Name,x.Phone));