web-dev-qa-db-fra.com

Convertir IEnumerable en DataTable

Existe-t-il un moyen intéressant de convertir un IEnumerable en DataTable?

Je pourrais utiliser la réflexion pour obtenir les propriétés et les valeurs, mais cela semble un peu inefficace, y a-t-il quelque chose d'intégré?

(Je connais des exemples du type: ObtainDataTableFromIEnumerable)} _

MODIFIER:
Cette question m'a informé d'un problème lié à la gestion des valeurs nulles.
Le code que j'ai écrit ci-dessous gère correctement les valeurs nulles.

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

Regardez celui-ci: Convertir la liste/IEnumerable en DataTable/DataView

Dans mon code je l'ai changé en une méthode d'extension:

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;
}
90
CD..

À tous:

Notez que la réponse acceptée contient un bogue concernant les types nullable et le DataTable. Le correctif est disponible sur le site lié ( http://www.chinhdo.com/20090402/convert-list-to-datatable/ ) ou dans mon code modifié ci-dessous:

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

Notez que ces deux exemples sont des méthodes d'extension ET NON PAS comme dans l'exemple ci-dessus.

Enfin ... Toutes mes excuses pour mes commentaires trop fréquents/excessifs (j'avais un prof/méchant qui me l'a battu!;)

16
Campbeln

Tout d'abord, vous devez ajouter une contrainte where T:class. Vous ne pouvez pas appeler GetValue sur les types de valeur, à moins qu'ils ne soient passés par ref.

Deuxièmement, GetValue est très lent et est souvent appelé.

Pour résoudre ce problème, nous pouvons créer un délégué et appeler à la place:

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

Le problème est que nous ne savons pas TProperty, mais comme d'habitude ici Jon Skeet a la réponse - nous pouvons utiliser la réflexion pour extraire le délégué getter, mais une fois que nous l'avons, nous n'avons pas besoin de réfléchir à nouveau:

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

Alors maintenant, votre méthode devient:

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

Vous pouvez l’optimiser davantage en stockant les getters de chaque type dans un dictionnaire statique. Dans ce cas, vous aurez uniquement le temps de réflexion nécessaire pour chaque type.

4
Keith

J'ai écrit une bibliothèque pour gérer cela pour moi. Il s’appelle DataTableProxy et est disponible sous la forme d’un package NuGet . Le code et la documentation sont sur Github

4
tom.dietrich

Il n'y a rien d'aussi bâti, mais le construire vous-même devrait être facile. Je voudrais faire ce que vous suggérez et utiliser réflexion pour obtenir les propriétés et les utiliser pour créer les colonnes du tableau. Ensuite, je passerais en revue chaque élément dans IEnumerable et créer une ligne pour chacun. Le seul inconvénient est que si votre collection contient des éléments de plusieurs types (par exemple, Personne et Animal), ils peuvent ne pas avoir les mêmes propriétés. Mais si vous devez vérifier cela dépend de votre utilisation.

0
Rune Grimstad

J'ai aussi rencontré ce problème. Dans mon cas, je ne connaissais pas le type de IEnumerable. Donc, les réponses données ci-dessus ne fonctionneront pas. Cependant, je l'ai résolu comme ceci:

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

N'oubliez pas que l'utilisation de cette méthode nécessite au moins un élément dans IEnumerable. Si ce n'est pas le cas, le DataTable ne créera aucune colonne.

0
Displee

Je résous ce problème en ajoutant une méthode d'extension à 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
Andrey Angerchik