c# - 将列表转换为 DataTable 时获取匿名类型
问题描述
我有一个列表,我在其中选择列TaskId
(全局变量)和EmpGuid
(从列表中),例如:
var parameterstest = assignNotificationTableType.Select(x => new { TaskId, x.EmpGuid }).ToList();
所以如果我调试我会得到这样的东西:
现在我创建了将其转换为 DataTable 的方法,例如:
public static 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);
if (Props.Length > 0)
{
foreach (PropertyInfo prop in Props)
{
if (GetDefault(prop.PropertyType.FullName) != null)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
}
else
{
dataTable.Columns.Add("myColName");
}
foreach (T item in items)
{
if (item != null)
{
DataRow dr = dataTable.NewRow();
if (Props.Length > 0)
{
foreach (PropertyInfo prop in Props)
{
if (GetDefault(prop.PropertyType.FullName) != null)
{
//inserting property values to datatable rows
dr[prop.Name] = prop.GetValue(item, null) ?? GetDefault(prop.PropertyType.FullName);
}
}
}
else
{
//inserting property values to datatable rows
dr[0] = item;
}
dataTable.Rows.Add(dr);
}
}
//put a breakpoint here and check datatable
return dataTable;
}
public static object GetDefault(string dataType)
{
if (dataType.Contains("System.String"))
{
return string.Empty;
}
if (dataType.Contains("System.Boolean"))
{
return false;
}
if (dataType.Contains("System.Decimal"))
{
return 0.0;
}
if (dataType.Contains("System.DateTime"))
{
return DateTime.MinValue;
}
if (dataType.Contains("System.Int64"))
{
return 0;
}
if (dataType.Contains("System.Guid"))
{
return null;
}
if (dataType.Contains("System.Int16"))
{
return 0;
}
if (dataType.Contains("Int32"))
{
return 0;
}
if (dataType.Contains("System.Object"))
{
return null;
}
return null;
}
但是当我尝试用作:
var parameters = ToDataTable(assignNotificationTableType.Select(x => new { TaskId, x.EmpGuid }).ToList());
变量返回{<>f__AnonymousType42}
而不是 DataTable
我不知道为什么它返回 AnonymousType。有人知道那里有什么问题吗?
更新
如您所见,匿名类型数据表正确计数行,但 ItemArray 始终为零,而不是我的值
解决方案
我解决了它,将我的 Convert DataTable 方法更改为:
public static DataTable ToSingleDataTable<T>(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);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
推荐阅读
- python - 如果数据框合并上的值相等,则在一行中追加列
- arm - 在符合 ABI 的 ARM 中的标签后是否需要冒号
- javascript - 通过对数组进行排序来确定数组是否有重复元素
- php - 在 PHP 中合并 pdf 文件并在其中保留网络链接
- java - 从具有颜色强度的双阵列创建图像
- php - 提交表单PHP MYSQL后出现空白页
- python - Rasa - 获取用于自定义操作的槽值
- javascript - if语句无法执行
- postgresql - 如何在 yocto 中构建支持 openSSL 的 PostgreSQL?
- arrays - 尝试在 reactjs 中组合 event.target.value 捕获的输入输入值