Get DataTable from IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Get DataTable from IEnumerable

Demo Code


using System.ComponentModel;
using System.Data;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//  w  w  w .ja  v  a2  s. co  m

public class Main{
        public static DataTable GetDataTable<T>(IEnumerable<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) ?? DBNull.Value;
                }
                table.Rows.Add(row);
            }
            return table;
        }
}

Related Tutorials