Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I need to convert DataRow again into DataRow?

Look into following code block,

DataTable _table = new DataTable();

//1) Why I need to Convert DataRow again into DataRow by Casting ?
List<DataRow> _rows = _table.Rows.Cast<DataRow>().Select(a => a).ToList();

//2) Why this is not valid?
List<DataRow> _rows = _table.Rows.Select(a => a).ToList();

In first case why I need to convert DataRow again into DataRow? and Why second case not valid?

like image 505
Ankush Madankar Avatar asked Dec 13 '13 05:12

Ankush Madankar


1 Answers

DataTable.Rows's return type, the DataRowCollection class, dates from the old, dark times before generics, and, thus, only implements IEnumerable rather than IEnumerable<DataRow>.

You can use the shiny new DataTable.AsEnumerable LINQ extension method instead, which returns an IEnumerable<DataRow>:

List<DataRow> _rows = _table.AsEnumerable().Select(a => a).ToList();

In fact, you do not need Select(a => a) at all:

List<DataRow> _rows = _table.AsEnumerable().ToList();

PS: There is a Microsoft Connect feature request to make DataRowCollection implement IEnumerable<DataRow>. However, since an easy alternative is available (AsEnumerable), they probably have other priorities.

like image 174
Heinzi Avatar answered Oct 11 '22 16:10

Heinzi