c#在json对象中组合列表
本文关键字:组合 列表 对象 json | 更新日期: 2023-09-27 18:08:16
我有两个字符串列表:
List<string> tmpCols = new List<string>();
List<string> tmpRows = new List<string>();
。tmpCols = [A,B,C];and 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列
这是一个教科书式的嵌套循环示例。循环可以包含其他循环,其中内部循环为外部循环的每个元素重复。这个可能看起来像:
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 });
我觉得这是个迟来的回答
需要迭代这两个列表并得到一个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"
}
]
使用以下代码解决:
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] });
}
}