Converter IEnumerable para DataTable

Existe uma boa maneira de converter um IEnumerable para um DataTable?

Eu poderia usar a reflection para obter as propriedades e os valores, mas isso parece um pouco ineficiente, existe algo embutido?

(Eu sei os exemplos como: ObtainDataTableFromIEnumerable)

EDITAR :
Esta questão notificou-me de um problema ao lidar com valores nulos.
O código que escrevi abaixo manipula corretamente os valores nulos.

public static DataTable ToDataTable(this IEnumerable 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; } 

   

    Olhe para este: Converter lista / IEnumerable para DataTable / DataView

    No meu código eu mudei para um método de extensão:

     public static DataTable ToDataTable(this List 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 

    Para todos:

    Observe que a resposta aceita tem um bug relacionado aos tipos anuláveis ​​e ao DataTable. A correção está disponível no site vinculado ( http://www.chinhdo.com/20090402/convert-list-to-datatable/ ) ou no meu código modificado abaixo:

      ///############################################################### ///  /// Convert a List to a DataTable. ///  ///  /// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "ToDataTable" /// Code modifications made by Nick Campbell. /// Source code provided on this web site (chinhdo.com) is under the MIT license. /// Copyright © 2010 Chinh Do /// 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: /// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. /// 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. /// (As per http://www.chinhdo.com/20080825/transactional-file-manager/) ///  /// Type representing the type to convert. /// List of requested type representing the values to convert. ///  ///############################################################### /// February 15, 2010 public static DataTable ToDataTable(List 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; } ///############################################################### ///  /// Returns the underlying/base type of nullable types. ///  ///  /// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "GetCoreType" /// Code modifications made by Nick Campbell. /// Source code provided on this web site (chinhdo.com) is under the MIT license. /// Copyright © 2010 Chinh Do /// 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: /// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. /// 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. /// (As per http://www.chinhdo.com/20080825/transactional-file-manager/) ///  /// Type representing the type to query. /// Type representing the underlying/base type. ///############################################################### /// February 15, 2010 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; } } 

    Note que ambos os exemplos não são methods de extensão como o exemplo acima.

    Por fim … desculpas por meus comentários extensivos / excessivos (eu tive um anal / prof médio que bateu em mim!)

    Em primeiro lugar, você precisa adicionar uma restrição de where T:class – não é possível chamar GetValue em tipos de valor, a menos que eles sejam passados ​​por ref .

    Em segundo lugar GetValue é muito lento e é chamado muito.

    Para contornar isso, podemos criar um delegado e chamar isso:

     MethodInfo method = property.GetGetMethod(true); Delegate.CreateDelegate(typeof(Func), method ); 

    O problema é que nós não sabemos TProperty , mas como de costume aqui Jon Skeet tem a resposta – podemos usar a reflection para recuperar o delegado getter, mas uma vez que tenhamos, não precisamos refletir novamente:

     public class ReflectionUtility { internal static Func GetGetter(PropertyInfo property) { // get the get method for the property MethodInfo method = property.GetGetMethod(true); // get the generic get-method generator (ReflectionUtility.GetSetterHelper) 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) ret; } static Func GetGetterHelper(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 func = (Func) Delegate.CreateDelegate(typeof(Func), method); // Now create a more weakly typed delegate which will call the strongly typed one Func ret = (object target) => (TResult) func((TTarget) target); return ret; } } 

    Então agora seu método se torna:

     public static DataTable ToDataTable(this IEnumerable items) where T: class { // ... create table the same way var propGetters = new List>(); foreach (var prop in props) { Func func = (Func) 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; } 

    Você poderia otimizá-lo ainda mais, armazenando os getters para cada tipo em um dictionary estático, então você só terá a sobrecarga de reflection uma vez para cada tipo.

    Eu escrevi uma biblioteca para lidar com isso para mim. É chamado DataTableProxy e está disponível como um pacote NuGet . Código e documentação estão no Github

    Não há nada construído em afaik, mas construir você mesmo deve ser fácil. Eu faria o que você sugere e usaria a reflection para obter as propriedades e usá-las para criar as colunas da tabela. Em seguida, passo através de cada item no IEnumerable e crie uma linha para cada um. A única ressalva é se a sua coleção contém itens de vários tipos (por exemplo, Person e Animal), então eles podem não ter as mesmas propriedades. Mas se você precisar verificar isso depende do seu uso.

    Eu resolvo esse problema adicionando o método de extensão ao IEnumerable.

     public static class DataTableEnumerate { public static void Fill (this IEnumerable 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); } } } 

    Eu também me deparei com esse problema. No meu caso, eu não sabia o tipo do IEnumerable. Então as respostas dadas acima não funcionarão. No entanto, eu resolvi assim:

     public static DataTable CreateDataTable(IEnumerable source) { var table = new DataTable(); int index = 0; var properties = new List(); 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; } 

    Tenha em mente que usar esse método requer pelo menos um item no IEnumerable. Se esse não for o caso, o DataTable não criará nenhuma coluna.