Преобразование IEnumerable в DataTable

Есть ли хороший способ преобразовать 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; 
} 

person Zyphrax    schedule 10.08.2009    source источник
comment
просто попробовал этот код с IEnumerable<Int64>, и он не работает, потому что строка PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); заканчивается на props == {System.Reflection.PropertyInfo[0]}, надеялся, что вы поможете мне разобраться, что не так   -  person Manatherin    schedule 22.03.2011
comment
@Manatherin: метод будет работать только со ссылками на объекты, а не с типами значений. Для типов значений это не имеет смысла, поскольку у вас есть только одно значение (а не несколько свойств, как со ссылками на объекты).   -  person Zyphrax    schedule 31.03.2011


Ответы (9)


Взгляните на это: Convert List / IEnumerable to 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;
}
person CD..    schedule 10.08.2009
comment
Что ж, это намного лучше, чем существующий материал ObtainDataTableFromIEnumerable - person Zyphrax; 10.08.2009
comment
Я бы только добавил изменение из List ‹T› в IEnumerable ‹T› - person Didaxis; 01.03.2012
comment
Это не работает, если тип является строкой, так как свойства - это символы и длина, но значение get затем пытается поместить полную строку в столбец char. - person Manatherin; 18.06.2013
comment
У меня была небольшая проблема с типами, допускающими значение NULL, которая была решена с помощью tb.Columns.Add (prop.Name, Nullable.GetUnderlyingType (prop.PropertyType) ?? prop.PropertyType); - person Henrique; 20.12.2019

Все:

Обратите внимание, что в принятом ответе есть ошибка, относящаяся к типам, допускающим значение NULL, и 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;
        }
    }

Обратите внимание, что оба этих примера - НЕ методы расширения, подобные приведенному выше.

Наконец ... извиняюсь за мои обширные / чрезмерные комментарии (у меня был анальный / средний проф, который вбил меня в меня!;)

person Campbeln    schedule 15.02.2010
comment
Спасибо! Я также столкнулся с нулевой проблемой. Вы можете проверить мое решение в вопросе. - person Zyphrax; 15.02.2010
comment
Мне нравятся ваши префиксы переменных. Это значительно упрощает чтение и понимание вашего кода. - person Ronnie Overby; 29.07.2010
comment
@Ronnie - Спасибо! Это действительно мой собственный стиль (который имеет тенденцию чаще доставлять мне неприятности, чем нет), но я тоже считаю, что это имеет ооочень много смысла! Я знаю утверждение M $ о том, что intellisense достаточно для переменных, но, если вы спросите меня, это чистая бабка. Отсюда и мои сильно искаженные венгерские обозначения. - person Campbeln; 10.02.2011
comment
Спасибо за это. Мне это действительно помогло. Но мне очень не нравятся префиксы переменных :) - person Rob Vermeulen; 06.11.2012
comment
В принятом ответе просто измените содержимое первого foreach на: tb.Columns.Add (Nullable.GetUnderlyingType (prop.PropertyType) ?? prop.PropertyType); - person OctoCode; 15.03.2017

Я написал библиотеку, чтобы справиться с этим за меня. Он называется DataTableProxy и доступен в виде пакета NuGet. Код и документация находятся на Github.

person tom.dietrich    schedule 02.02.2013

Во-первых, вам нужно добавить ограничение where T:class - вы не можете вызывать GetValue для типов значений, если они не переданы ref.

Во-вторых, GetValue очень медленный и часто вызывается.

Чтобы обойти это, мы можем создать делегата и вместо этого вызвать его:

MethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );

Проблема в том, что мы не знаем TProperty, но, как обычно, здесь У Джона Скита есть ответ - мы можем использовать отражение для получения делегата-получателя, но как только мы получим это нам не нужно снова размышлять:

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

Вы можете дополнительно оптимизировать его, сохранив геттеры для каждого типа в статическом словаре, тогда у вас будут накладные расходы на отражение только один раз для каждого типа.

person Keith    schedule 19.05.2011

Я тоже столкнулся с этой проблемой. В моем случае я не знал тип 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 не будет создавать никаких столбцов.

person Displee    schedule 16.04.2018

Итак, спустя 10 лет это все еще актуально :)

Я пробовал все ответы на этой странице (ATOW)
, а также некоторые решения на базе ILGenerator (FastMember и Fast.Reflection).
Но скомпилированное лямбда-выражение кажется самым быстрым.
По крайней мере, для моих случаев использования (в .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;
    }
}

Работает только со свойствами (не полями), но работает с анонимными типами.

person Florian Fida    schedule 21.09.2019

Ответ 2019 года, если вы используете .NET Core - используйте библиотеку Nuget ToDataTable. Преимущества:

Заявление об ограничении ответственности - я являюсь автором ToDataTable

Производительность. Я провел несколько тестов Benchmark .Net и включил их в Репозиторий ToDataTable. Результаты были следующими:

Создание таблицы данных на 100 000 строк:

Reflection                 818.5 ms
DataTableProxy           1,068.8 ms
ToDataTable                449.0 ms
person Chris HG    schedule 05.10.2019

В afaik нет ничего встроенного, но собрать его самому должно быть легко. Я бы сделал то, что вы предлагаете, и использовал бы отражение, чтобы получить свойства и использовать их для создания столбцов таблицы. Затем я перебирал каждый элемент в IEnumerable и создавал для каждого строку. Единственное предостережение: если ваша коллекция содержит элементы нескольких типов (например, человек и животное), они могут иметь разные свойства. Но если вам нужно проверить, это зависит от вашего использования.

person Rune Grimstad    schedule 10.08.2009

Я решаю эту проблему, добавляя метод расширения в 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);
        }

    }
}
person Andrey Angerchik    schedule 02.06.2017