如何用 List<T> 填充数据表 [英] How to fill a datatable with List<T>

查看:32
本文介绍了如何用 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&lt;T&gt; 填充数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆