相关疑难解决方法(0)

.NET - 将通用集合转换为DataTable

我试图将通用集合(List)转换为DataTable.我找到了以下代码来帮助我这样做:

// Sorry about indentation
public class CollectionHelper
{
private CollectionHelper()
{
}

// this is the method I have been using
public static DataTable ConvertTo<T>(IList<T> list)
{
    DataTable table = CreateTable<T>();
    Type entityType = typeof(T);
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

    foreach (T item in list)
    {
        DataRow row = table.NewRow();

        foreach (PropertyDescriptor prop in properties)
        {
            row[prop.Name] = prop.GetValue(item);
        }

        table.Rows.Add(row);
    }

    return table;
}    

public static DataTable CreateTable<T>()
{
    Type entityType = typeof(T);
    DataTable table = new DataTable(entityType.Name);
    PropertyDescriptorCollection …
Run Code Online (Sandbox Code Playgroud)

c# generics collections datatable nullable

74
推荐指数
4
解决办法
7万
查看次数

标签 统计

c# ×1

collections ×1

datatable ×1

generics ×1

nullable ×1