【发布时间】:2026-02-06 13:50:01
【问题描述】:
enter image description here我正在尝试将我的List 转换为DataTable,但在转换时记录数变为0。
这是我的代码:
DataAccessProvider dap = new DataAccessProvider(
Settings.Default.SQLServerConnection,
DatabaseType.MSSql);
var employees = dap.SelectAll("Employees").AsEnumerable().ToList();
DataTable Employees = new DataTable();
Employees = ToDataTable(employees);
public DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(
BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
public List<dynamic> SelectAll(string tableName)
{
List<dynamic> result = new List<dynamic>();
using (IDataReader reader = ExecuteReader("Select * From " + tableName))
{
while (reader.Read())
{
dynamic expando = new ExpandoObject();
for (int i = 0; i < reader.FieldCount; i++)
{
string columnName = reader.GetName(i);
((IDictionary<String, Object>)expando).Add(
columnName,
reader[columnName]);
}
result.Add(expando);
}
}
return result;
}
以上都是我的代码。当我调试时,我发现在 ToDataTable 函数中,Props 计数为 0。那么这里有什么问题?
【问题讨论】:
-
您不必实现自己的
ToDataTable方法,因为您可以使用ToDataTable扩展方法,但您需要先安装MoreLinq。检查此答案以了解*.com/a/42550827/2946329 -
@S.Akbari - 好像这个问题包含它自己的一个名为
ToDataTable的方法的实现@ -
@Jamiec 是的,我猜 OP 已经不知道
ToDataTable扩展方法了。 -
@Jamiec 建议某人使用现有库而不是编写自己的代码来做某事是一个有效的评论,也许不是一个好的答案,但它绝对是一个可以接受的评论。
-
@Jamiec 这与天气有关,问题好坏,而不是评论好坏。 cmets 的全部意义在于要求澄清或提出作为答案无效的建议。