8

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
Trevor Reid
  • 3,310
  • 4
  • 27
  • 46
AG70
  • 874
  • 1
  • 9
  • 23
  • Try to avoid the `dynamic` type. Its very slow and its not type-safe. – akop May 15 '19 at 07:31
  • 2
    Possible duplicate of [How do I reflect over the members of dynamic object?](https://stackoverflow.com/questions/2634858/how-do-i-reflect-over-the-members-of-dynamic-object) – GSerg May 15 '19 at 07:57

1 Answers1

7

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();
        }
    }
}
Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34