2015-08-16 47 views
-6

我有串的兩個列表:C#結合起來,JSON對象列出

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

例如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列。

+0

你嘗試過什麼解決問題了嗎?有沒有任何代碼? –

+0

我曾嘗試使用兩個基本的循環,但沒有成功。 – user2633804

+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

使用此代碼解決:

 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] }); 
      } 

     } 
+0

與json沒有任何關係。 – EZI

+0

@EZI這是因爲這個問題與JSON無關 – Rob

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); 

OUTPUT:

[ 
    { 
    "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" 
    } 
]