.NET - Convert Generic Collection to DataTable

前端 未结 5 1693
感情败类
感情败类 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: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(this IEnumerable collection, string tableName)
            {
                DataTable tbl = ToDataTable(collection);
                tbl.TableName = tableName;
                return tbl;
            }
    
            public static DataTable ToDataTable(this IEnumerable 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;
            }
    
        }
    }
    

提交回复
热议问题