.NET - Convert Generic Collection to DataTable

前端 未结 5 1677
感情败类
感情败类 2020-11-27 10:17

I am trying to convert a generic collection (List) to a DataTable. I found the following code to help me do this:

// Sorry about indentation
public class Col         


        
相关标签:
5条回答
  • 2020-11-27 10:46

    Then presumably you'll need to lift them to the non-nullable form, using Nullable.GetUnderlyingType, and perhaps change a few null values to DbNull.Value...

    Change the assignment to be:

    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
    

    and when adding the columns to be:

    table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
                prop.PropertyType) ?? prop.PropertyType);
    

    And it works. (?? is the null-coalescing operator; it uses the first operand if it is non-null, else the second operand is evaluated and used)

    0 讨论(0)
  • 2020-11-27 10:55

    I know this question is old, but I had the same issue for an extension method I made. Using the response from Marc Gravell, I was able to modify my code. This extension method will handle lists of primitive types, strings, enumerations and objects with primitive properties.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Linq;
    using System.Text;
    
    /// <summary>
    /// Converts a List&lt;T&gt; to a DataTable.
    /// </summary>
    /// <typeparam name="T">The type of the list collection.</typeparam>
    /// <param name="list">List instance reference.</param>
    /// <returns>A DataTable of the converted list collection.</returns>
    public static DataTable ToDataTable<T>(this List<T> list)
    {
        var entityType = typeof (T);
    
        // Lists of type System.String and System.Enum (which includes enumerations and structs) must be handled differently 
        // than primitives and custom objects (e.g. an object that is not type System.Object).
        if (entityType == typeof (String))
        {
            var dataTable = new DataTable(entityType.Name);
            dataTable.Columns.Add(entityType.Name);
    
            // Iterate through each item in the list. There is only one cell, so use index 0 to set the value.
            foreach (T item in list)
            {
                var row = dataTable.NewRow();
                row[0] = item;
                dataTable.Rows.Add(row);
            }
    
            return dataTable;
        }
        else if (entityType.BaseType == typeof (Enum))
        {
            var dataTable = new DataTable(entityType.Name);
            dataTable.Columns.Add(entityType.Name);
    
            // Iterate through each item in the list. There is only one cell, so use index 0 to set the value.
            foreach (string namedConstant in Enum.GetNames(entityType))
            {
                var row = dataTable.NewRow();
                row[0] = namedConstant;
                dataTable.Rows.Add(row);
            }
    
            return dataTable;
        }
    
        // Check if the type of the list is a primitive type or not. Note that if the type of the list is a custom 
        // object (e.g. an object that is not type System.Object), the underlying type will be null.
        var underlyingType = Nullable.GetUnderlyingType(entityType);
        var primitiveTypes = new List<Type>
        {
            typeof (Byte),
            typeof (Char),
            typeof (Decimal),
            typeof (Double),
            typeof (Int16),
            typeof (Int32),
            typeof (Int64),
            typeof (SByte),
            typeof (Single),
            typeof (UInt16),
            typeof (UInt32),
            typeof (UInt64),
        };
    
        var typeIsPrimitive = primitiveTypes.Contains(underlyingType);
    
        // If the type of the list is a primitive, perform a simple conversion.
        // Otherwise, map the object's properties to columns and fill the cells with the properties' values.
        if (typeIsPrimitive)
        {
            var dataTable = new DataTable(underlyingType.Name);
            dataTable.Columns.Add(underlyingType.Name);
    
            // Iterate through each item in the list. There is only one cell, so use index 0 to set the value.
            foreach (T item in list)
            {
                var row = dataTable.NewRow();
                row[0] = item;
                dataTable.Rows.Add(row);
            }
    
            return dataTable;
        }
        else
        {
            // TODO:
            // 1. Convert lists of type System.Object to a data table.
            // 2. Handle objects with nested objects (make the column name the name of the object and print "system.object" as the value).
    
            var dataTable = new DataTable(entityType.Name);
            var propertyDescriptorCollection = TypeDescriptor.GetProperties(entityType);
    
            // Iterate through each property in the object and add that property name as a new column in the data table.
            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptorCollection)
            {
                // Data tables cannot have nullable columns. The cells can have null values, but the actual columns themselves cannot be nullable.
                // Therefore, if the current property type is nullable, use the underlying type (e.g. if the type is a nullable int, use int).
                var propertyType = Nullable.GetUnderlyingType(propertyDescriptor.PropertyType) ?? propertyDescriptor.PropertyType;
                dataTable.Columns.Add(propertyDescriptor.Name, propertyType);
            }
    
            // Iterate through each object in the list adn add a new row in the data table.
            // Then iterate through each property in the object and add the property's value to the current cell.
            // Once all properties in the current object have been used, add the row to the data table.
            foreach (T item in list)
            {
                var row = dataTable.NewRow();
    
                foreach (PropertyDescriptor propertyDescriptor in propertyDescriptorCollection)
                {
                    var value = propertyDescriptor.GetValue(item);
                    row[propertyDescriptor.Name] = value ?? DBNull.Value;
                }
    
                dataTable.Rows.Add(row);
            }
    
            return dataTable;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 10:59

    Well. Since DataSet does not support nullable types, you'd have to check if the property is a generic type, get the generic definition of that type and then get the argument (which is the actual type) using, perhaps, Nullable.GetUnderlyingType. If the value is null, just use DBNull.Value in the DataSet.

    0 讨论(0)
  • 2020-11-27 10:59

    Here's a version with some modifications to allow for nulls and '\0' characters without blowing up the DataTable.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Data;
    
    namespace SomeNamespace
    {
        public static class Extenders
        {
            public static DataTable ToDataTable<T>(this IEnumerable<T> collection, string tableName)
            {
                DataTable tbl = ToDataTable(collection);
                tbl.TableName = tableName;
                return tbl;
            }
    
            public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
            {
                DataTable dt = new DataTable();
                Type t = typeof(T);
                PropertyInfo[] pia = t.GetProperties();
                object temp;
                DataRow dr;
    
                for (int i = 0; i < pia.Length; i++ )
                {
                    dt.Columns.Add(pia[i].Name, Nullable.GetUnderlyingType(pia[i].PropertyType) ?? pia[i].PropertyType);
                    dt.Columns[i].AllowDBNull = true;
                }
    
                //Populate the table
                foreach (T item in collection)
                {
                    dr = dt.NewRow();
                    dr.BeginEdit();
    
                    for (int i = 0; i < pia.Length; i++)
                    {
                        temp = pia[i].GetValue(item, null);
                        if (temp == null || (temp.GetType().Name == "Char" && ((char)temp).Equals('\0')))
                        {
                            dr[pia[i].Name] = (object)DBNull.Value;
                        }
                        else
                        {
                            dr[pia[i].Name] = temp;
                        }
                    }
    
                    dr.EndEdit();
                    dt.Rows.Add(dr);
                }
                return dt;
            }
    
        }
    }
    
    0 讨论(0)
  • 2020-11-27 11:08

    If Nullable.GetUnderlyingType() given your prop.PropertyType returns a not-null value, use that as the type of a column. Otherwise, use prop.PropertyType itself.

    0 讨论(0)
提交回复
热议问题