添加通用列表

时间:2016-08-03 10:13:15

标签: c# json datatable

我正在尝试将DataTable中的所有数据添加到我已编写c#代码的List<string> dataFromDataTable = new List<string>();中。稍后我需要将其转换为Json。

这是代码。

List<string> dataFromDataTable = new List<string>();

for (int r = 0; r < employees.Rows.Count; r++)
{
   dataFromDataTable.Add("{".ToString());
   for (int c = 0; c < employees.Columns.Count; c++)
    {
      dataFromDataTable.Add(employees.Rows[r][c].ToString());
    }
   dataFromDataTable.Add("}".ToString());
}

这是我的json代码。

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(sample);

截至目前,我正在得到json。

["John Doe","Fresno","Billy","Fresno","Tom","Kern","King Smith","Kings"]

而我需要它像

["John Doe","Fresno"],["Billy","Fresno"],["Tom","Kern"],["King Smith","Kings"]]

如何消除它。谢谢

2 个答案:

答案 0 :(得分:1)

var data = employees.AsEnumerable().Select(x => x.ItemArray).ToList();
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);

希望这会有所帮助

答案 1 :(得分:0)

我通常会这样做:

  var list = employees.AsEnumerable().Select(row =>
            new 
            {
                FirstName = row.Field<string>("FirstName"), // Column name was not specified please change this
                LastName = row.Field<string>("LastName") // As well as this column
            }).ToList();

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(list);

请注意,最好在对象中添加键,以便添加FirstNameLastName示例。