Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<List<string>> to a DataTable

How would I convert List<List<string>> to a DataTable? I am trying to set the DataSource of a gridview to a List<List<string>> variable.

like image 301
Hazior Avatar asked Jun 14 '11 14:06

Hazior


People also ask

How to convert List to DataTable?

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.

How to convert List of string to DataTable in c#?

Method We introduce the ConvertListToDataTable method, which converts a List<string[]> to a DataTable. Here We create a new empty DataTable. Next, we find the maximum number of columns that will be required by looping through the input List. Then We add those columns, and then add all the rows.

How do I convert a list into a DataFrame in R?

data. frame() can be used to convert a list to R DataFrame or create a data frame from a list. If you want the elements in the list column-wise, then use cbind otherwise you can use rbind. Also learned to use different third-party packages to create DataFrame from a list.


2 Answers

This can easily be done using extension methods.

Add this class to your solution

static class ListExtensions
{
    public static DataTable ToDataTable(this List<List<string>> list)
    {
        DataTable tmp = new DataTable();
        foreach (List<string> row in list)
        {
            tmp.Rows.Add(row.ToArray());
        }
        return tmp;
    }
}

then use the extension method like this:

List<List<string>> myList = new List<List<string>>();
// Fill with values...
DataTable table = myList.ToDataTable();
like image 52
rickythefox Avatar answered Sep 29 '22 23:09

rickythefox


I would rather set DataSource of the grid to BindableList, which you would perhaps create easier, instead of double nested List, you would have List of Rows (where the Row is business entity represented, for example Customer).

like image 36
Denis Biondic Avatar answered Sep 29 '22 23:09

Denis Biondic