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.
the CSV file contains this data:
Id,Name,Barnd
1,one,abc
2,two,xyz
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.
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.
Normally, dynamic
type has a System.Dynamic.ExpandoObject
type object while using it. Its same as a KeyValuePair
type 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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With