>许多C#开发人员遇到将通用列表转换为DataTables的挑战。虽然反射提供了解决方案,但存在更有效的方法。 本文探讨了最佳方法。
为了出色的性能,强烈建议使用FastMember库(通过Nuget获得):
<code class="language-csharp">IEnumerable<sometype> data = ...; DataTable table = new DataTable(); using(var reader = ObjectReader.Create(data)) { table.Load(reader); }</code>
性能优化:超删除者
<code class="language-csharp">public static DataTable ToDataTable<T>(this IList<T> data) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); DataTable table = new DataTable(); for (int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } foreach (T item in data) { DataRow row = table.NewRow(); for (int i = 0; i < props.Count; i++) { row[i] = props[i].GetValue(item); } table.Rows.Add(row); } return table; }</code>
标准方法:27179 ms
以上是如何有效地将通用列表转换为C#中的数据列表?的详细内容。更多信息请关注PHP中文网其他相关文章!