C# 将IEnumerable转换为DataTable

C# 将IEnumerable转换为DataTable,c#,datatable,ienumerable,C#,Datatable,Ienumerable,有没有很好的方法将IEnumerable转换为DataTable 我可以使用反射来获取属性和值,但这似乎有点低效,是否有内置的东西 (我知道这样的例子:从IEnumerable获得DataTable) 编辑: 这通知我处理空值时出现问题。 我在下面编写的代码正确地处理空值 public static DataTable ToDataTable<T>(this IEnumerable<T> items) { // Create the result table,

有没有很好的方法将IEnumerable转换为DataTable

我可以使用反射来获取属性和值,但这似乎有点低效,是否有内置的东西

(我知道这样的例子:从IEnumerable获得DataTable)

编辑
这通知我处理空值时出现问题。
我在下面编写的代码正确地处理空值

public static DataTable ToDataTable<T>(this IEnumerable<T> items) {  
    // Create the result table, and gather all properties of a T        
    DataTable table = new DataTable(typeof(T).Name); 
    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  

    // Add the properties as columns to the datatable
    foreach (var prop in props) { 
        Type propType = prop.PropertyType; 

        // Is it a nullable type? Get the underlying type 
        if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
            propType = new NullableConverter(propType).UnderlyingType;  

        table.Columns.Add(prop.Name, propType); 
    }  

    // Add the property values per T as rows to the datatable
    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);   

        table.Rows.Add(values);  
    } 

    return table; 
} 
公共静态数据表到数据表(此IEnumerable items){
//创建结果表,并收集T的所有属性
DataTable=新的DataTable(typeof(T).Name);
PropertyInfo[]props=typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
//将属性作为列添加到datatable
foreach(props中的var prop){
类型propType=prop.PropertyType;
//它是可为null的类型吗?获取基础类型
if(propType.IsGenericType&&propType.GetGenericTypeDefinition().Equals(typeof(null)))
propType=新的NullableConverter(propType).UnderlinedType;
table.Columns.Add(prop.Name,propType);
}  
//将每个T的属性值作为行添加到datatable中
foreach(项目中的变量项目){
var值=新对象[props.Length];
对于(变量i=0;i
看看这个:

在我的代码中,我将其更改为扩展方法:

public static DataTable ToDataTable<T>(this List<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;
}
公共静态数据表到数据表(此列表项)
{
var tb=新数据表(typeof(T).Name);
PropertyInfo[]props=typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(道具中的var道具)
{
tb.Columns.Add(prop.Name,prop.PropertyType);
}
foreach(项目中的var项目)
{
var值=新对象[props.Length];

对于(var i=0;iafaik中没有内置任何内容,但是自己构建应该很容易。我会按照您的建议,使用反射来获取属性并使用它们创建表的列。然后我会逐步遍历IEnumerable中的每个项,并为每个项创建一行。唯一需要注意的是,如果您的集合包含seve项ral类型(例如人和动物)可能不具有相同的属性。但如果需要检查,则取决于您的使用。

所有人:

请注意,接受的答案中有一个与nullable类型和DataTable相关的错误。修复程序可在链接站点()或下面我修改的代码中找到:

    ///###############################################################
    /// <summary>
    /// Convert a List to a DataTable.
    /// </summary>
    /// <remarks>
    /// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "ToDataTable"
    /// <para/>Code modifications made by Nick Campbell.
    /// <para/>Source code provided on this web site (chinhdo.com) is under the MIT license.
    /// <para/>Copyright © 2010 Chinh Do
    /// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    /// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    /// <para/>THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    /// <para/>(As per http://www.chinhdo.com/20080825/transactional-file-manager/)
    /// </remarks>
    /// <typeparam name="T">Type representing the type to convert.</typeparam>
    /// <param name="l_oItems">List of requested type representing the values to convert.</param>
    /// <returns></returns>
    ///###############################################################
    /// <LastUpdated>February 15, 2010</LastUpdated>
    public static DataTable ToDataTable<T>(List<T> l_oItems) {
        DataTable oReturn = new DataTable(typeof(T).Name);
        object[] a_oValues;
        int i;

            //#### Collect the a_oProperties for the passed T
        PropertyInfo[] a_oProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            //#### Traverse each oProperty, .Add'ing each .Name/.BaseType into our oReturn value
            //####     NOTE: The call to .BaseType is required as DataTables/DataSets do not support nullable types, so it's non-nullable counterpart Type is required in the .Column definition
        foreach(PropertyInfo oProperty in a_oProperties) {
            oReturn.Columns.Add(oProperty.Name, BaseType(oProperty.PropertyType));
        }

            //#### Traverse the l_oItems
        foreach (T oItem in l_oItems) {
                //#### Collect the a_oValues for this loop
            a_oValues = new object[a_oProperties.Length];

                //#### Traverse the a_oProperties, populating each a_oValues as we go
            for (i = 0; i < a_oProperties.Length; i++) {
                a_oValues[i] = a_oProperties[i].GetValue(oItem, null);
            }

                //#### .Add the .Row that represents the current a_oValues into our oReturn value
            oReturn.Rows.Add(a_oValues);
        }

            //#### Return the above determined oReturn value to the caller
        return oReturn;
    }

    ///###############################################################
    /// <summary>
    /// Returns the underlying/base type of nullable types.
    /// </summary>
    /// <remarks>
    /// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "GetCoreType"
    /// <para/>Code modifications made by Nick Campbell.
    /// <para/>Source code provided on this web site (chinhdo.com) is under the MIT license.
    /// <para/>Copyright © 2010 Chinh Do
    /// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    /// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    /// <para/>THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    /// <para/>(As per http://www.chinhdo.com/20080825/transactional-file-manager/)
    /// </remarks>
    /// <param name="oType">Type representing the type to query.</param>
    /// <returns>Type representing the underlying/base type.</returns>
    ///###############################################################
    /// <LastUpdated>February 15, 2010</LastUpdated>
    public static Type BaseType(Type oType) {
            //#### If the passed oType is valid, .IsValueType and is logicially nullable, .Get(its)UnderlyingType
        if (oType != null && oType.IsValueType &&
            oType.IsGenericType && oType.GetGenericTypeDefinition() == typeof(Nullable<>)
        ) {
            return Nullable.GetUnderlyingType(oType);
        }
            //#### Else the passed oType was null or was not logicially nullable, so simply return the passed oType
        else {
            return oType;
        }
    }
///###############################################################
/// 
///将列表转换为数据表。
/// 
/// 
///基于麻省理工学院许可代码,在http://www.chinhdo.com/20090402/convert-list-to-datatable/ 作为“ToDataTable”
///尼克·坎贝尔修改的代码。
///本网站(chinhdo.com)提供的源代码是麻省理工学院许可的。
///版权所有©2010 Chinh Do
///特此向获得本软件及相关文档文件(“软件”)副本的任何人免费授予许可,不受限制地经营本软件,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售本软件副本的权利,并允许向其提供本软件的人员这样做,但须符合以下条件:
///上述版权声明和本许可声明应包含在软件的所有副本或实质部分中。
///软件按“原样”提供,无任何形式的明示或暗示保证,包括但不限于适销性、特定用途适用性和非侵权性保证。在任何情况下,作者或版权持有人均不对因以下原因引起的任何索赔、损害赔偿或其他责任负责,无论是合同诉讼、侵权诉讼还是其他诉讼:R与软件或软件的使用或其他交易有关。
///(根据http://www.chinhdo.com/20080825/transactional-file-manager/)
/// 
///表示要转换的类型的类型。
///表示要转换的值的请求类型列表。
/// 
///###############################################################
///2010年2月15日
公共静态数据表到数据表(列表项){
DataTable oReturn=新数据表(typeof(T).Name);
对象[]a_oValues;
int i;
//####收集已通过测试的a_属性
PropertyInfo[]a_oProperties=typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
//####遍历每个OpProperty,将每个.Name/.BaseType添加到我们的oReturn值中
//####注意:对.BaseType的调用是必需的,因为DataTables/Dataset不支持可为null的类型,因此在.Column定义中需要不可为null的对应类型
foreach(a_oProperties中的财产信息){
oReturn.Columns.Add(opProperty.Name,BaseType(opProperty.PropertyType));
}
//####穿过l_oItems
foreach(在l_oItems中的T oItem){
//####收集此循环的a_值
a_oValues=新对象[a_oProperties.Length];
//####遍历a_属性,边走边填充每个a_值
对于(i=0;iMethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );
public class ReflectionUtility
{
    internal static Func<object, object> GetGetter(PropertyInfo property)
    {
        // get the get method for the property
        MethodInfo method = property.GetGetMethod(true);

        // get the generic get-method generator (ReflectionUtility.GetSetterHelper<TTarget, TValue>)
        MethodInfo genericHelper = typeof(ReflectionUtility).GetMethod(
            "GetGetterHelper",
            BindingFlags.Static | BindingFlags.NonPublic);

        // reflection call to the generic get-method generator to generate the type arguments
        MethodInfo constructedHelper = genericHelper.MakeGenericMethod(
            method.DeclaringType,
            method.ReturnType);

        // now call it. The null argument is because it's a static method.
        object ret = constructedHelper.Invoke(null, new object[] { method });

        // cast the result to the action delegate and return it
        return (Func<object, object>) ret;
    }

    static Func<object, object> GetGetterHelper<TTarget, TResult>(MethodInfo method)
        where TTarget : class // target must be a class as property sets on structs need a ref param
    {
        // Convert the slow MethodInfo into a fast, strongly typed, open delegate
        Func<TTarget, TResult> func = (Func<TTarget, TResult>) Delegate.CreateDelegate(typeof(Func<TTarget, TResult>), method);

        // Now create a more weakly typed delegate which will call the strongly typed one
        Func<object, object> ret = (object target) => (TResult) func((TTarget) target);
        return ret;
    }
}
public static DataTable ToDataTable<T>(this IEnumerable<T> items) 
    where T: class
{  
    // ... create table the same way

    var propGetters = new List<Func<T, object>>();
foreach (var prop in props)
    {
        Func<T, object> func = (Func<T, object>) ReflectionUtility.GetGetter(prop);
        propGetters.Add(func);
    }

    // Add the property values per T as rows to the datatable
    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);   
            values[i] = propGetters[i](item);
        }    

        table.Rows.Add(values);  
    } 

    return table; 
} 
public static class DataTableEnumerate
{
    public static void Fill<T> (this IEnumerable<T> Ts, ref DataTable dt) where T : class
    {
        //Get Enumerable Type
        Type tT = typeof(T);

        //Get Collection of NoVirtual properties
        var T_props = tT.GetProperties().Where(p => !p.GetGetMethod().IsVirtual).ToArray();

        //Fill Schema
        foreach (PropertyInfo p in T_props)
            dt.Columns.Add(p.Name, p.GetMethod.ReturnParameter.ParameterType.BaseType);

        //Fill Data
        foreach (T t in Ts)
        {
            DataRow row = dt.NewRow();

            foreach (PropertyInfo p in T_props)
                row[p.Name] = p.GetValue(t);

            dt.Rows.Add(row);
        }

    }
}
public static DataTable CreateDataTable(IEnumerable source)
    {
        var table = new DataTable();
        int index = 0;
        var properties = new List<PropertyInfo>();
        foreach (var obj in source)
        {
            if (index == 0)
            {
                foreach (var property in obj.GetType().GetProperties())
                {
                    if (Nullable.GetUnderlyingType(property.PropertyType) != null)
                    {
                        continue;
                    }
                    properties.Add(property);
                    table.Columns.Add(new DataColumn(property.Name, property.PropertyType));
                }
            }
            object[] values = new object[properties.Count];
            for (int i = 0; i < properties.Count; i++)
            {
                values[i] = properties[i].GetValue(obj);
            }
            table.Rows.Add(values);
            index++;
        }
        return table;
    }
Reflection                 818.5 ms
DataTableProxy           1,068.8 ms
ToDataTable                449.0 ms