2
using (var sr = new StreamReader("myfile.csv"))
{
    var reader = new CsvReader(sr);
    List<dynamic> csvRecords = reader.GetRecords<dynamic>().ToList();

    //this works
    foreach (var row in csvRecords)
    {
        foreach (var item in row)
        {
            var z = item.Value;
        }
    }

    //this should work, error message below
    foreach (var row in csvRecords)
    {
        var z = row[0].Value;
    }
}

ERROR

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot apply indexing with [] to an expression of type 'System.Dynamic.ExpandoObject

dbc
  • 104,963
  • 20
  • 228
  • 340
001
  • 62,807
  • 94
  • 230
  • 350

2 Answers2

1

According to documentation you can get fields using Read()

using (var reader = new StreamReader("myfile.csv")) {
    var csv = new CsvReader( reader );
    while(csv.Read()) {//This will advance the reader to the next record.
    
        //You can use an indexer to get by position or name. 
        //This will return the field as a string

        // By position
        var field = csv[0];

        // By header name
        var field = csv["HeaderName"];
    }
}

Reference https://joshclose.github.io/CsvHelper/reading#getting-fields

dbc
  • 104,963
  • 20
  • 228
  • 340
Nkosi
  • 235,767
  • 35
  • 427
  • 472
0

Your row implements IDictionary<String, object> interface explicitly, so to get the value, you have to cast the row instance first, and then to use ElementAt(0).Value, or to address the value by its column name:

//this works fine
foreach (IDictionary<string, object> row in csvRecords)
{
     var z = row["column name"];
}

//and this works too 
foreach (IDictionary<string, object> row in csvRecords)
{
      var z = row.ElementAt(0).Value;
}
d_f
  • 4,599
  • 2
  • 23
  • 34