如何将List <List <string >>转换为数据表

Haz*_*ior 4 c# asp.net visual-studio

我将如何转换List<List<string>>DataTable?我试图将DataSourcegridview的设置为List<List<string>>变量。

ric*_*fox 5

使用扩展方法可以轻松完成此操作。

将此类添加到您的解决方案中

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用如下扩展方法:

List<List<string>> myList = new List<List<string>>();
// Fill with values...
DataTable table = myList.ToDataTable();
Run Code Online (Sandbox Code Playgroud)