Ankush Madankar
Ankush Madankar

Reputation: 3834

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?

Upvotes: 5

Views: 1340

Answers (1)

Heinzi
Heinzi

Reputation: 172280

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.

Upvotes: 5

Related Questions