c# - 将列表转换为 DataTable 后数据丢失
问题描述
我创建一个Guid
这样的新列表:
List<Guid> EmpGuid = new List<Guid>();
然后我填充它:
foreach (DataRowView list in lstTech.SelectedItems)
{
var empGuid = (Guid)list[0];
EmpGuid.Add(empGuid);
}
一旦有了项目,我将其转换为DataTable
:
var parameters = ToDataTable(EmpGuid);
ToDataTable
方法:
public static DataTable ToDataTable<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;
}
问题是当我将它转换为 时DataTable
,它会创建 2 行,但是有空行没有我的值EmpGuid
。任何人都知道它为什么会发生?
解决方案
只需添加此函数并调用它,它会将 List 转换为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;
}
推荐阅读
- c# - efcore 2.2 中的多租户配置
- wordpress - Wordpress 管理区域,添加固定弹出窗口的最佳操作
- python - 基于熊猫列数的自定义分组
- linux - Linux 排序与编程
- selenium - 选择文件和输入文本关键字在 Robot Framework Selenium 中不起作用
- python - Python:如何优化或简化以下代码?
- ubuntu - Gnome Tweak Tool 不保存更改
- excel - 在 VBA WinHttpRequest 上捕获超时
- java - Web 应用程序运行正常但重新启动计算机返回:源服务器未找到目标资源的当前表示
- opencart - Opencart v3 调用 webhook