1

Ir am trying to render content that is loaded from a CSV with Scriban. Unfortunately, its not rendering correctly unless I explicitly call ToDictionary to create another dictionary and I would like to understand why, and proper ways to fix it.

var reader = new StreamReader(csvFile.ToString());
var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
var records = csv.GetRecords<dynamic>();
    
var templateStr = "|{{ReportID}}|";

foreach(ExpandoObject record in records){
    var template = Template.Parse(templateStr);
    var row = (IDictionary<string,object>)record;

    var reportID = row["ReportID"]; // Works as dictionary

    var expando = template.Render(record);
    var expandoCast = template.Render(row);
    var expandoToDictionary = template.Render(record.ToDictionary(x=>x.Key, x=>x.Value));

    Console.WriteLine($"{reportID} expando: {expando} expandoCast:{expandoCast} expandoToDictionary:{expandoToDictionary}");  
}

Prints

3940268 expando: || expandoCast:|| expandoToDictionary:|3940268|

Why does the template not render the keys? Is there a better way to solve this without creating a new dictionary?

jmerkow
  • 1,811
  • 3
  • 20
  • 35
  • What happens if you cast to Dictionary instead of IDictionary? – JOSEFtw Jun 28 '21 at 04:59
  • I get this error: `error CS0039: Cannot convert type 'System.Dynamic.ExpandoObject' to 'System.Collections.Generic.Dictionary' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion` – jmerkow Jun 28 '21 at 05:03
  • And if you try passing your expandoobject to the dictionary constructor like this? var row = new Dictionary(record); – JOSEFtw Jun 28 '21 at 06:15
  • This seems to work. Will this connect the row to the original object or make a copy? – jmerkow Jun 30 '21 at 15:02

0 Answers0