所以我想将一些值写入3列中的csv文件,如下所示:
number of series firstVal secondVal
10 23 33
50 55 66
100 98 102
我将所有myvalues存储在字典中
var timeResults = new Dictionary<string, Dictionary<string, double>>();
和mycode是这样的:
foreach (var resultSet in timeResults)
{
var csv = new StringBuilder();
csv.AppendLine(String.Format("Number of TimeSeries;{0}", n));
foreach (var result in resultSet.Value)
{
csv.AppendLine(String.Format("{0}.{1} (ms);{2}", resultSet.Key, result.Key, result.Value));
}
File.AppendAllText(@"D:/CSV/Results_" + resultSet.Key + ".csv", csv.ToString());
}
但我得到的是这样的:
Number of TimeSeries 10
add.firstVal(ms) 74
add.secondVal (ms) 12
Number of TimeSeries 50
add.firstVal (ms) 4
add.secondVal(ms) 3
Number of TimeSeries 100
add.firstVal (ms) 6
add.secondVal (ms) 6
我想做的就是告诉它去第一行,但是下一栏再写一遍。所以所有的值都在一列中。怎么可能?
答案 0 :(得分:1)
编写和阅读CVS文件本身并不是一项简单的任务。最好使用像CsvHelper和A Fast CSV Reader
这样的图书馆此外,字典不保证您获得记录的顺序。这对你来说可能是一个问题。请考虑使用List代替或按某些条件对记录进行排序。
所以,你的代码可能是这样的
stream = new MemoryStream();
writer = new StreamWriter(stream);
csvWriter = new CsvWriter(writer);
csvWriter.Configuration.QuoteAllFields = false;
csvWriter.Configuration.HasHeaderRecord = true;
csvWriter.WriteField("Number of TimeSeries");
csvWriter.WriteField("add.firstVal(ms)");
csvWriter.WriteField("add.secondVal (ms)");
csvWriter.NextRecord();
foreach (var resultSet in timeResults)
{
csvWriter.WriteField(resultSet.Key);
foreach (var result in resultSet.Value)
{
csvWriter.WriteField(result.Key);
csvWriter.WriteField(result.Value));
}
csvWriter.NextRecord();
}
writer.Flush();
// do what you need with the data in the stream.
// dispose objects.