views:

24009

answers:

6

Currently, I'm using:

DataTable dt = CreateDataTableInSomeWay();

List<DataRow> list = new List<DataRow>(); 
foreach (DataRow dr in dt.Rows)
{
    list.Add(dr);
}

Is there a better/magic way?

+6  A: 

You could use

List<DataRow> list = new List<DataRow>(dt.select());

dt.select() will return all rows in your table, as an array of datarows, and the List constructor accepts that array of objects as an argument to initially fill your list with.

Kibbee
Select() doesn't need any parameters. The parameterless overload would return all rows.
Kon
Thanks, adjusting my answer to fit your sugguestion
Kibbee
+5  A: 

With C# 3.0 and System.Data.DataSetExtensions.dll,

List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();
Marc Gravell
+19  A: 

If you're using .NET 3.5, you can use DataTableExtensions.AsEnumerable (an extension method) and then if you really need a List<DataRow> instead of just IEnumerable<DataRow> you can call Enumerable.ToList:

IEnumerable<DataRow> sequence = dt.AsEnumerable();

or

List<DataRow> list = dt.AsEnumerable().ToList();
Jon Skeet
Splendid. Exactly what I was after. Thanks all for the answers.
IainMH
@jon how to convert this `list` to json.
Pandiya Chendur
@Pandiya: There are various ways of converting data into JSON in .NET. Personally I've always used the JSON.NET library, but there are other approaches too.
Jon Skeet
@jon http://stackoverflow.com/questions/3482261/how-to-convert-c-generic-list-to-json-using-json-net
Pandiya Chendur
A: 

A more 'magic' way, and doesn't need .NET 3.5.

If, for example, DBDatatable was returning a single column of GUIDs (uniqueidentifier in SQL) then you could use:

        Dim gList As New List(Of Guid)
        gList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))
A: 

DataTable.Select() doesnt give the Rows in the order they were present in the datatable.

If order is important I feel iterating over the datarow collection and forming a List is the right way to go or you could also use overload of DataTable.Select(string filterexpression, string sort). but this overload may not handle all the ordering(like order by case ...) that SQL provides.

A: 

Again, using 3.5 you may do it like:

dt.Select().ToList()

BRGDS

gjsduarte