c# - 从类(而不是实例列表)创建数据表
这个问题涉及泛型和类型以及数据表。
下面的代码片段在网上随处可见,它创建了一个基于通用类型的数据表:
public static DataTable ListToDataTable<T>(List<T> list)
{
DataTable dt = new DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
我正在使用出色的 FileHelpers 库将批量记录导入到 SQL Server 中。要使用 SqlBulkCopy,我需要一个包含给定类型列的数据表。 Filehelpers 可以在运行时读取 .cs 文件并基于该文件创建您的类型。例如:
System.Type userType = null;
userType = ClassBuilder.ClassFromSourceFile("myclassfile.cs");
我想更改上面的方法,以便它在传递类型(例如“userType”)时为我创建列。即方法签名将类似于:
public static DataTable TypeToDataTable<T>(<T> myType)
并将返回一个包含列的空数据集,准备将 userType 行添加到其中。
我尝试过各种方法 - 有什么想法吗?
This question concerns generics and types as well as datatables.
The following snippet is around the net here and there, and creates a datatable based on a generic type:
public static DataTable ListToDataTable<T>(List<T> list)
{
DataTable dt = new DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
I'm using the excellent FileHelpers library to import batches of records into SQL Server. To use SqlBulkCopy I need a datatable with columns from a given type. Filehelpers can read in a .cs file at runtime and create your type based on that. eg:
System.Type userType = null;
userType = ClassBuilder.ClassFromSourceFile("myclassfile.cs");
I'd like to change the method above so it just creates the columns for me when passed a type (eg 'userType'). ie the method signature would be something like:
public static DataTable TypeToDataTable<T>(<T> myType)
and would return an empty dataset with columns, ready to have rows of userType added to it.
I've tried various methods - any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它实际上非常简单,当您意识到在这种情况下不需要(甚至可以)使用泛型时:
您可以这样调用它:
It's actually pretty simple, when you realize that you don't need to (or even can) use generics in this case:
You would call it like this:
最近我正是需要这个,并在 SO 上找到了它。我将问题的前提与答案结合起来,并决定共享代码,因为两者都不完整:
Recently I needed exactly this and found it here on SO. I combined the premise in the question with the answer and decided to share the code since both are incomplete: