我的问题是我有一个foreach循环,它将每行数据保存到List中,然后从列表中创建TXT,问题是我的数据以这种形式保存到TXT中:
["ROW1","DATA1","DATA2","DATA3","ROW2","DATA4","DATA5","DATA6"]
我想让我的txt拥有这样的数据:
[["ROW1","DATA1","DATA2","DATA3"],["ROW2","DATA4","DATA5","DATA6"]]
将每一行放入单独的附加括号(“[]”)中,如何在不使用其他列表的情况下执行此操作?
这是我的Foreach循环:
List<string> listaprocedure = new List<string>();
foreach (DataRow dato in myTable.Rows)
{
foreach (DataColumn datoC in myTable.Columns)
{
listaprocedure.Add(dato[datoC].ToString());
}
}
json4 = JsonConvert.SerializeObject(procedimiento2);
System.IO.File.WriteAllText(@"C:\procedure.txt", json4);
答案 0 :(得分:1)
您可以手动迭代行,在读取每个行时写入每个行,然后在其后添加,
(最后一行除外)。另外,在开头和结尾添加[
和]
。
相当丑陋,但如果你处理真正的大桌子可以帮助。
但最好的选择是填充List<List<string>>
(或string[,]
)。
无论如何,这是一个有效的例子:
using (var reader = File.CreateText("C:\\procedure.txt"))
{
// Starting outer json array
reader.WriteLine("[");
for (var rowIndex = 0; rowIndex < myTable.Rows.Count; rowIndex++)
{
var row = myTable.Rows[rowIndex];
var rowValues = new List<string>(); // can be reused if needed
foreach (DataColumn column in myTable.Columns)
rowValues.Add(row[column].ToString());
var jsonRow = JsonConvert.SerializeObject(rowValues);
// Write current row
reader.Write(jsonRow);
// Add separating comma
if (rowIndex != myTable.Rows.Count - 1)
reader.WriteLine(",");
}
// End outer json array
reader.WriteLine("]");
}
答案 1 :(得分:0)
根据您的样本数据,这有效:
var query =
from dr in myTable.Rows.OfType<DataRow>()
from dc in myTable.Columns.OfType<DataColumn>()
group dr[dc].ToString() by dc.Ordinal / 4;
var json4 = JsonConvert.SerializeObject(query);
这给了我:
[["ROW1","DATA1","DATA2","DATA3"],["ROW2","DATA4","DATA5","DATA6"]]
我使用此代码初始化我的数据:
var myTable = new DataTable();
myTable.Columns.Add("A1", typeof(string));
myTable.Columns.Add("A2", typeof(string));
myTable.Columns.Add("A3", typeof(string));
myTable.Columns.Add("A4", typeof(string));
myTable.Columns.Add("B1", typeof(string));
myTable.Columns.Add("B2", typeof(string));
myTable.Columns.Add("B3", typeof(string));
myTable.Columns.Add("B4", typeof(string));
myTable.Rows.Add("ROW1", "DATA1", "DATA2", "DATA3", "ROW2", "DATA4", "DATA5", "DATA6");