I use CSV writer and it work great for most part. When I try to write the object which has a list, it ignores writing the list only. for eg.below, it writes all the attributes of the Trade object except the Wave which is a List of Wave objects
my class trade has following including a list Wave.
class Trade
{
public string symbol { get; set; }
public bool isOpen { get; set; }
public DateTime OpenTime { get; set; }
public DateTime CloseTime { get; set; }
public double mfe { get; set; }
public double mae { get; set; }
public double entryPrice { get; set; }
public double exitprice { get; set; }
public TradeP TradeSignal { get; set; }
public string comments { get; set; }
public int Days2Stop { get; set; }
public double TimeBreakout { get; set; }
public double r { get; set; }
public int daysreach1r { get; set; }
public int daysreach9x50 { get; set; }
public double maetill1r { get; set; }
public bool Day1ClosedDown { get; set; }
public List<Wave> Waves { get; set; }
}
// write all the trade objects
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\temp\" + DateTime.Now.ToString("yyyyMMdd") + "traderesults.txt", true))
{
var csv = new CsvWriter(file);
csv.WriteRecords(Trades);
}
In the screenshot above, you can see the csv writer prints all the object attributes. its pretty long but at the end it does not print the attribute of the Wave objects
CSV file is flat. How would you represent such record, if you had to create a file manually. You would have to repeat records. Which does not make sense, so library is doing a right thing here by ignoring Waves
.
Workaround would be to have another property in your class that returns you the comma separated values for a property in Wave
object, say Prop1
(string
).
class Trade {
//..
public string WaveCSV {
get {
return string.Join(",", Waves.Select(w => w.Prop1).ToArray());
}
}
}
You will need to qualify WaveCSV
with "
so that comma within the value doesn't harm, or use a different separator altogether.
Edit:
If you need more than one property, then you can override ToString()
in Wave
class, return whatever you want, and use w.ToString()
instead.