C#组合在json对象中列出

时间:2015-08-16 20:46:40

标签: c# json

我有两个字符串列表:

        List<string> tmpCols = new List<string>();
        List<string> tmpRows = new List<string>();

e.g。 tmpCols = [A,B,C];和tmpRows = [X,Y];

我需要迭代这两个列表并获得这样的Json结果:

        new matrix() { id = "1", col = "A", row = "X" });
        new matrix() { id = "2", col = "B", row = "X" });
        new matrix() { id = "3", col = "C", row = "X" });
        new matrix() { id = "4", col = "A", row = "Y" });
        new matrix() { id = "5", col = "B", row = "Y" });
        new matrix() { id = "6", col = "C", row = "Y" });

这种情况下的维度为2行3列。

3 个答案:

答案 0 :(得分:2)

这是嵌套循环的教科书示例。循环可以包含其他循环,其中内部循环对于外部循环的每个元素重复。这可能看起来像:

var result = new List<matrix>();
var count = 1;
foreach (var r in tmpRows)
    foreach (var c in tmpCols)
        result.Add(new matrix { id = (count++).ToString(), col = c, row = r });

答案 1 :(得分:2)

我认为这是一个迟到的答案

  

需要迭代这两个列表并获得这样的Json结果:

这不是json,我想你想要这样的东西

List<string> tmpCols = new List<string>() { "A", "B", "C" };
List<string> tmpRows = new List<string>() { "X", "Y" };

var query = tmpCols.SelectMany(c => tmpRows.Select(r => new {id=index++, col=c, row = r }));
var json = JsonConvert.SerializeObject(query, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);

<强>输出:

[
  {
    "id": 6,
    "col": "A",
    "row": "X"
  },
  {
    "id": 7,
    "col": "A",
    "row": "Y"
  },
  {
    "id": 8,
    "col": "B",
    "row": "X"
  },
  {
    "id": 9,
    "col": "B",
    "row": "Y"
  },
  {
    "id": 10,
    "col": "C",
    "row": "X"
  },
  {
    "id": 11,
    "col": "C",
    "row": "Y"
  }
]

答案 2 :(得分:-1)

使用此代码解决:

        var tmpMatrix = new List<matrix>();

        for (int k = 0; k < tmpRows.Count; k++)
        {

            for (int j = 0; j < tmpCols.Count; j++)
            {
                int ident = k*tmpCols.Count + j;
                tmpMatrix.Add(new matrix() { id = ident.ToString(), col = tmpCols[j], row = tmpRows[k] });
            }

        }