C#将每列的值转换为数组

时间:2016-03-28 22:06:53

标签: c# .net json linq

我想转换一个C#对象或数据表,使每个列成为一个键和一个键。值变为数组

year    productOne     ProductTwo      ProductThree
2010    1              2                 3
2011    10             20                30
2012    100            200               300
2013    1000           2000              3000

我希望生成以下JSON输出。请记住,行和列都不是动态的。

[{
    name: productOne ,
    data: [1,10,100,1000]
},{
    name: productTwo ,
    data: [2,20,200,2000]
},{
    name: productThree ,
    data: [3,30,300,3000]
}]

2 个答案:

答案 0 :(得分:3)

DataTable dt = new DataTable();
            dt.Columns.Add("col1");
            dt.Columns.Add("col2");
            dt.Columns.Add("col3");

            DataRow dr = dt.NewRow();
            dr[0] = "10";
            dr[1] = "20";
            dr[2] = "30";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr[0] = "100";
            dr[1] = "200";
            dr[2] = "300";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr[0] = "1000";
            dr[1] = "2000";
            dr[2] = "3000";
            dt.Rows.Add(dr);

            List<dynamic> list = new List<dynamic>();

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                dynamic result = new ExpandoObject();
                result.name = dt.Columns[i].ColumnName;
                result.data = dt.Rows.Cast<DataRow>()
                               .Select(row => row[i])
                               .ToArray();
                list.Add(result);
            }

            var op = JsonConvert.SerializeObject(list);

答案 1 :(得分:1)

你绝对可以在列表和词典的帮助下完成这项工作。

public static IDictionary<string, List<object>> TransposeDataTable(DataTable table)
{

    if (table == null) {
        return null;
    }

    var dicData = new Dictionary<string, List<object>> ();
    var lstRows = new List<object>[table.Columns.Count];

    foreach (DataRow item in table.Rows) {
        for (var i = 0; i < table.Columns.Count; i++) {
            if (lstRows [i] == null) {
                lstRows [i] = new List<object> ();
            }
            lstRows [i].Add (item [i]); 
        }
    }

    for (var i = 0; i < table.Columns.Count; i++) {
        dicData.Add (table.Columns [i].ColumnName, lstRows [i]);
    }

    return dicData;
}

上面的代码将从表的列名创建字典键,每列的数据将进入相应的列表。这是一种元组。

我们假设您的DataTable是有效的dt

var dataObject = TransposeDataTable (dt);
var jsonString = JsonConvert.SerializeObject (dataObject, Formatting.Indented);

转换成功后,jsonString将包含我们漂亮的Json对象。在我的例子中,dt作为虚拟数据,因此会产生类似的东西。

{
    "year": [
        "2010",
        "2011",
        "2012",
        "2013",
        "2014"
    ],
    "produceOne": [
        "1",
        "11",
        "21",
        "31",
        "41"
    ],
    "ProductTwo": [
        "2",
        "12",
        "22",
        "32",
        "42"
    ],
    "ProductThree": [
        "3",
        "13",
        "23",
        "33",
        "43"
    ]
}