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.
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.
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.
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.
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();
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With