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

查看:108
本文介绍了如何填充列表℃的数据表; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表如何转换成一个DataTable

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;
    }
}

我试着使用:

I tried using:

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;
         }

这篇关于如何填充列表℃的数据表; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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