我们可以将列表转换为C#中的DataTable吗? [英] Can we convert the list into DataTable in C#?

查看:66
本文介绍了我们可以将列表转换为C#中的DataTable吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

任何人都可以告诉我如何将列表< T> 转换为 DataTable ?

推荐答案

示例代码将向您显示转换为通用列表 Datatable

你必须使用 Reflaction

The Sample code will show you about conversion to Generic List to Datatable.
You will have to use Reflaction for that.
public static DataTable ToDataTable<T>(this 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;        
}



投票 接受答复 如果它已帮助。


Please vote and Accept Answer if it Helped.


为Hiren的代码我们需要使用...

for Hiren''s code we need to use...
using System.Collections.Generic;
using System.ComponentModel;



谢谢Hiren


Thanks Hiren




考虑你有一个像

Hi,
Consider you have a list like
    List<string> countries = new List<string>();
    countries.Add("India");
    countries.Add("Pakistan");
    countries.Add("USA");

    DataTable workTable = new DataTable("Countries");
    DataColumn column;   DataRow row;
    column = new DataColumn();
    column.DataType = System.Type.GetType("System.String");
    column.ColumnName = "CountryName";
    column.AutoIncrement = false;
    column.Caption = "ParentItem";
    column.ReadOnly = false;
    column.Unique = false;
    // Add the column to the table.
    workTable.Columns.Add(column);

for(int i=0; i<=countries.length; i++)
{  
    workTable = table.NewRow();
    workTable["CountryName"] = (String) countries[i];
    workTable.Rows.Add(row);
}


这篇关于我们可以将列表转换为C#中的DataTable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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