如何转换List <keyvaluepair <string,decimal =“”>&gt; list = new List <keyvaluepair <string,decimal =“”>&gt;();到DataTable?</keyvaluepair <string,> </keyvaluepair <string,>

时间:2014-02-10 07:25:52

标签: c# wpf wpf-controls

我有一个清单

List<> list = new List<>();

我想将其转换为数据表。怎么可能?

1 个答案:

答案 0 :(得分:0)

以下是将任何列表对象转换为数据表的方法。

 public DataTable ConvertToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection properties =
           TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;

    }

http://social.msdn.microsoft.com/Forums/vstudio/en-US/6ffcb247-77fb-40b4-bcba-08ba377ab9db/converting-a-list-to-datatable?forum=csharpgeneral