将IEnumerable转换为DataTable

72

有没有一种好的方法将IEnumerable转换为DataTable?

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

(我知道像:ObtainDataTableFromIEnumerable的例子)

编辑:
这个问题提醒了我处理空值的问题。
我下面写的代码可以正确处理空值。

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<Int64> 的代码,但是它并没有起作用,因为这行代码 PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 结束时显示 props == {System.Reflection.PropertyInfo[0]}。希望您能帮我找出问题所在。 - Manatherin
1
@Manatherin:该方法仅适用于对象引用,而不适用于值类型。对于值类型来说,这是没有意义的,因为您只有一个值(而不是像对象引用一样具有多个属性)。 - Yvo
10个回答

118
看这个链接:将List/IEnumerable转换为DataTable/DataView 在我的代码中,我把它改成了扩展方法:
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;
}

这比现有的从IEnumerable获取DataTable的东西要好得多。 - Yvo
23
我只想补充一点,将List<T>改为IEnumerable<T>。 - Didaxis
如果类型是字符串,则此方法无法正常工作,因为属性是字符和长度,但获取的值会尝试将整个字符串放入字符列中。 - Manatherin
4
我刚刚遇到了一个关于可空类型的小问题,通过tb.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType)解决了。 - Henrique

20

致所有人:

请注意,被接受的答案存在与Nullable类型和DataTable相关的问题。修复方法可以在链接的网站 (http://www.chinhdo.com/20090402/convert-list-to-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;
        }
    }

请注意,这两个示例不是像上面的示例那样的扩展方法。
最后......抱歉我的评论太多了(我有一个苛刻的教授,他把这种习惯灌输给了我!;)

谢谢!我也遇到了空指针问题。你可以在问题中查看我的解决方案。 - Yvo
7
我喜欢你的变量前缀,它使你的代码更易于阅读和理解。 - Ronnie Overby
@Ronnie - 谢谢!这确实是我的个人风格(往往会让我陷入麻烦),但我也发现它非常有意义!我知道微软声称智能感知对于变量来说已经足够了,但如果你问我,那纯粹是胡说八道。因此,我采用了大量改编的匈牙利命名法。 - Campbeln
10
谢谢这份资料,它帮助了我很多。不过,我真的不喜欢变量前缀 :) - Rob Vermeulen
1
在被接受的答案中,只需更改第一个foreach的内容为:tb.Columns.Add(Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); - OctoCode

6
我已经写了一个库来处理这个问题。它叫做DataTableProxy,可以作为NuGet包下载。代码和文档在Github上。

5
首先,您需要添加一个“where T:class”约束-如果未通过“ref”传递值类型,则无法调用GetValue。
其次,GetValue非常缓慢并且被频繁调用。
为了解决这个问题,我们可以创建一个委托并调用它。
MethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );

问题在于我们不知道 TProperty 是什么,但通常在这里 Jon Skeet有答案 - 我们可以使用反射来检索getter委托,但一旦我们拥有它,我们就不需要再次反射:
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; 
} 

你可以通过将每种类型的getter存储在静态字典中来进一步优化它,然后每种类型只需要进行一次反射开销。

3

所以,十年后这仍然是一个问题 :)

我尝试了此页面上的每个答案(ATOW)
还尝试了一些由ILGenerator驱动的解决方案(FastMemberFast.Reflection)。
但编译的Lambda表达式似乎是最快的。
至少对于我的用例(在.Net Core 2.2上)。

这是我现在正在使用的内容:

public static class EnumerableExtensions {

    internal static Func<TClass, object> CompileGetter<TClass>(string propertyName) {
        var param = Expression.Parameter(typeof(TClass));
        var body = Expression.Convert(Expression.Property(param, propertyName), typeof(object));
        return Expression.Lambda<Func<TClass, object>>(body,param).Compile();
    }     

    public static DataTable ToDataTable<T>(this IEnumerable<T> collection) {
        var dataTable = new DataTable();
        var properties = typeof(T)
                        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                        .Where(p => p.CanRead)
                        .ToArray();

        if (properties.Length < 1) return null;
        var getters = new Func<T, object>[properties.Length];

        for (var i = 0; i < properties.Length; i++) {
            var columnType = Nullable.GetUnderlyingType(properties[i].PropertyType) ?? properties[i].PropertyType;
            dataTable.Columns.Add(properties[i].Name, columnType);
            getters[i] = CompileGetter<T>(properties[i].Name);
        }

        foreach (var row in collection) {
            var dtRow = new object[properties.Length];
            for (var i = 0; i < properties.Length; i++) {
                dtRow[i] = getters[i].Invoke(row) ?? DBNull.Value;
            }
            dataTable.Rows.Add(dtRow);
        }

        return dataTable;
    }
}

仅适用于属性(不适用于字段),但它可用于匿名类型。


2

1

我也遇到了这个问题。在我的情况下,我不知道IEnumerable的类型。所以上面给出的答案不起作用。然而,我是这样解决的:

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;
    }

请记住,使用此方法需要至少一个IEnumerable中的项目。如果不是这种情况,则DataTable将不会创建任何列。

1

0
我通过为IEnumerable添加扩展方法来解决这个问题。
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);
        }

    }
}

0

据我所知,没有内置的东西,但自己构建应该很容易。我会按照您的建议使用反射获取属性并使用它们来创建表的列。然后,我会遍历 IEnumerable 中的每个项目,并为每个项目创建一行。唯一的注意事项是,如果您的集合包含几种类型的项目(例如 Person 和 Animal),则它们可能没有相同的属性。但如果需要检查它,则取决于您的使用情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接