Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently convert DataSet.Tables to List<DataTable>?

I see many posts about converting the table(s) in a DataSet to a list of DataRows or other row data but I was unable to find anything about this question. This is what I came up with using .Net 3.0:

    public static List<DataTable> DataSetToList(DataSet ds)
    {
        List<DataTable> result = new List<DataTable>();

        foreach (DataTable dtbl in ds.Tables)
        {
            result.Add(dtbl);
        }

        return result;
    }

Is there a better way, excluding an extension method?

Thanks

like image 299
Soenhay Avatar asked Oct 21 '13 21:10

Soenhay


People also ask

Can we convert DataTable to list?

There are the following 3 ways to convert a DataTable to a List. Using a Loop. Using LINQ. Using a Generic Method.

How get data from DataSet to DataTable in VB net?

A DataSet already contains DataTables . You can just use: DataTable firstTable = dataSet. Tables[0];

How copy data from list to DataTable in C#?

Step 1: Create a console application and add the Student class with the properties as below. Step 2: In Main method, create a list of students as below. Step 3: Now we are going to convert this list object to a DataTable. For that we need to create a new class and a conversion method as below.


1 Answers

Based on Why LINQ casting with a Data.DataTableCollection this will work;

List<DataTable> result = new List<DataTable>(ds.Tables.Cast<DataTable>())
like image 137
Dave Anderson Avatar answered Sep 29 '22 08:09

Dave Anderson