Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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
like image 477
AG70 Avatar asked May 15 '19 07:05

AG70


People also ask

What is a property value C#?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.

What is method and property in C#?

C# properties are class members that expose functionality of methods using the syntax of fields. They simplify the syntax of calling traditional get and set methods (a.k.a. accessor methods). Like methods, they can be static or instance.


1 Answers

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();
        }
    }
}
like image 191
Gaurang Dave Avatar answered Sep 21 '22 13:09

Gaurang Dave