Convertir DataRowCollection a IEnumerable


Me gustaría hacer algo como esto en.NET 3.5. ¿Cuál es la forma más rápida?

IEnumerable<DataRow> collection = 
    TypedDataSet.TypedTableBase<DataRow>.Rows as IEnumerable<DataRow>;
Author: FMFF, 2011-02-12

4 answers

Asumiendo que está usando. NET 4.0, que introduce covarianza:

// Presumably your table is of some type deriving from TypedTableBase<T>,
// where T is an auto-generated type deriving from DataRow.
IEnumerable<DataRow> collection = myTypedTable;

El propio tipo de tabla implementa IEnumerable<T> where T : DataRow.

De lo contrario:

IEnumerable<DataRow> collection = myTypedTable.Cast<DataRow>();
 55
Author: Dan Tao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-11 21:20:37

Puede llamar a OfType<DataRow>() en el DataRowCollection.

 76
Author: wsanville,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-11 21:20:21

Una solución directa simple es usar el método "Select()" de un Sistema.Datos.Objeto DataTable, que produce " DataRow []". A partir de esto se puede tratar como un Linumberable usando Linq como a continuación:

List<MyItem> items = dtItems.Select().Select(row => new MyItem(row)).ToList();

Proporciona una lista útil de objetos para cada fila.

 2
Author: Michael Erickson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-09 01:42:24

Hay un método de extensión incorporado si incluye System.Data.DataSetExtensions.dll en su proyecto que agrega un método AsEnumerable().

IEnumerable<DataRow> collection = TypedDataSet.TypedTableBase<DataRow>.AsEnumerable();
 0
Author: Scott Chamberlain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-10 21:14:43