简体   繁体   English

使用CsvHelper时如何从C#Dynamic对象获取属性名称和值?

[英]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.

相关问题 通过字符串从 C# 动态 object 获取属性值(反射?) - Get property value from C# dynamic object by string (reflection?) 如何从对象中获取属性和值的名称并将此名称和值传递给 c# 中的列表 - How can i get the name of property and value from object and pass this name and value to a list in c# 在c#中通过属性名动态从类的对象中获取值 - Get the value from object of a class by property name dynamically in c# 如何通过属性名称字符串使用动态从Com互操作对象获取/设置值 - how to get/set value from Com interop object using dynamic by property name string CSVHelper 使用 object 属性值写入 header - CSVHelper write header using object property value C#使用自定义属性从对象获取属性值 - C# get property value from object using custom attribute 如何获取动态名称类型在C#中的变量中的动态类型的属性值 - How to get property value of a dynamic type where property name is in a variable in C# c#如何获取动态对象中的第n个对象属性名 - c# How to obtain the nth object property name in a dynamic object 如何在C#中使用反射从类型和设置属性值中按名称获取属性 - How can I Get the property by name from type and Set Propert value using reflection in C# CSVHelper C#从我的对象加载 - CSVHelper C# Load from My object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM