[英]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. 我正在使用CsvHelper将CSV文件读入Dynamic C#对象,我想使用
foreach
迭代List<dynamic>
并获取属性名称和值。
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. 总是返回0,但我可以在调试中看到有属性。
the CSV file contains this data: CSV文件包含以下数据:
Id,Name,Barnd
1,one,abc
2,two,xyz
Normally, dynamic
type has a System.Dynamic.ExpandoObject
type object while using it. 通常,
dynamic
类型在使用时具有System.Dynamic.ExpandoObject
类型对象。 Its same as a KeyValuePair
type in C#
. 它与
C#
的KeyValuePair
类型相同。
Following solution will return list of keys and values from dynamic
type. 以下解决方案将返回
dynamic
类型的键和值列表。
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.