The method below converts an array of objects to a DataTable object in C#.

Posted 吴晓阳

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了The method below converts an array of objects to a DataTable object in C#.相关的知识,希望对你有一定的参考价值。

http://www.c-sharpcorner.com/blogs/dynamic-objects-conveting-into-data-table-in-c-sharp1

public static DataTable GetDataTableFromObjects(object[] objects)
{
    if (objects != null && objects.Length > 0)
    {
        Type t = objects[0].GetType();
        DataTable dt = new DataTable(t.Name);
        foreach (PropertyInfo pi in t.GetProperties())
        {
            dt.Columns.Add(new DataColumn(pi.Name));
        }
        foreach (var o in objects)
        {
            DataRow dr = dt.NewRow();
            foreach (DataColumn dc in dt.Columns)
            {
                dr[dc.ColumnName] = o.GetType().GetProperty(dc.ColumnName).GetValue(o, null);
            }
            dt.Rows.Add(dr);
        }
        return dt;
    }
    return null;
}

 

        /// <summary>
        /// ToDataTable
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="items">实体集</param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(this IEnumerable<T> items)
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var prop in props)
            {
                tb.Columns.Add(prop.Name, prop.PropertyType);
            }

            foreach (var item in items)
            {
                var values = new object[props.Length];
                for (var i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }

 

以上是关于The method below converts an array of objects to a DataTable object in C#.的主要内容,如果未能解决你的问题,请参考以下文章

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and th

Cannot switch on a value of type String for source level below 1.7. Only convertible int values or e

The specified Android SDK Build Tools version (29.0.0) is ignored, as it is below the minimum suppor

Use the PDFs below or the HTML contents to the left to install and configure P6 EPPM and its additio

The query below helps you to locate tables without a primary key:

LINQ to Entities does not recognize the method , and this method cannot be translated into a store e