How to fill a datatable with Listlt;Tgt;(如何用 Listlt;Tgt; 填充数据表)
本文介绍了如何用 List<T> 填充数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将列表转换为数据表
How can convert a list to a datatable
[Serializable]
public class Item
{
public string Name { get; set; }
public double Price { get; set; }
public string @URL { get; set; }
public Item(string Name, string Price, string @URL)
{
this.Name = Name;
this.Price = Convert.ToDouble(Price);
this.@URL = @URL;
}
public override string ToString()
{
return this.Name;
}
}
我尝试使用:
static DataTable ConvertToDatatable(List<Item> list)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Price");
dt.Columns.Add("URL");
foreach (var item in list)
{
dt.Rows.Add(item.Name, Convert.ToString(item.Price), item.URL);
}
return dt;
}
现在我看到了一个盒子,但它是空的!帮助!!我该怎么做才能让盒子真正有数据?
Now I'm getting a box show up but its empty! Help!! What can i do to make the box actually have data?
推荐答案
以防万一你的类对象中有一个可为空的属性:
Just in case you have a nullable property in your class object:
private static DataTable ConvertToDatatable<T>(List<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]);
else
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;
}
这篇关于如何用 List<T> 填充数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何用 List<T> 填充数据表


猜你喜欢
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01