Search code examples
c#csvhelper

How to get property name and value from C# Dynamic object when using CsvHelper?


I am using CsvHelper to read CSV files into Dynamic C# object and I would like to iterate the List<dynamic> using foreach and get property names and values.

FileInfo file = new FileInfo("C:\\Temp\\CSVTest.csv");

List<dynamic> dynObj;

using (var reader = new StreamReader(file.FullName))
using (var csv = new CsvReader(reader))
{
    dynObj = csv.GetRecords<dynamic>().ToList();

    foreach (var d in dynObj)
    {
        var properties = d.GetType().GetProperties();
        foreach (var property in properties)
        {
            var PropertyName = property.Name;
            var PropetyValue = d.GetType().GetProperty(property.Name).GetValue(d, null);
         }
     }
 }

var properties = d.GetType().GetProperties(); always return 0 but I can see at debug that there are properties.

enter image description here

the CSV file contains this data:

Id,Name,Barnd
1,one,abc
2,two,xyz

Solution

  • Normally, dynamic type has a System.Dynamic.ExpandoObject type object while using it. Its same as a KeyValuePairtype in C#.

    Following solution will return list of keys and values from dynamic type.

    using (var csv = new CsvReader(reader))
    {
        dynObj = csv.GetRecords<dynamic>().ToList();
    
        foreach (var d in dynObj)
        {
            var obj = d as System.Dynamic.ExpandoObject;
    
            if (obj != null)
            {
                var keys = obj.Select(a => a.Key).ToList();
                var values = obj.Select(a => a.Value).ToList();
            }
        }
    }