映射到字典

Mat*_*att 2 c# csvhelper

我试图映射一个csv文件,以便每个记录都只是一个字典。

我收到ArgumentException“不是成员访问权”;当我尝试这样做时。代码如下:

public class CsvFileReader : FileReader
{
    public CsvFileReader(string path) : base(path){ }

    public IDictionary<string, object> Read()
    {
        var reader = new CsvReader(new StreamReader(Path));
        reader.Read();
        reader.Configuration.RegisterClassMap(new DictionaryClassMap(reader.FieldHeaders));
        return reader.GetRecord<Dictionary<string, object>>();
    }

    private class DictionaryClassMap : CsvClassMap<Dictionary<string, object>>
    {
        private readonly IEnumerable<string> _headers;

        public DictionaryClassMap(IEnumerable<string> headers)
        {
            _headers = headers;
        }

        public override void CreateMap()
        {
            foreach (var header in _headers)
            {
                var localHeader = header;
                Map(x => x[localHeader]);
            }
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ose 5

不幸的是,当前不支持映射到Dictionary

如果尝试这样做GetRecords<Dictionary<string, object>>(),将会出现错误。

Types that inhererit IEnumerable cannot be auto mapped. Did you accidentally call GetRecord or WriteRecord which acts on a single record instead of calling GetRecords or WriteRecords which acts on a list of records?
Run Code Online (Sandbox Code Playgroud)

您无法映射到Dictionary任何一个。在映射中,您需要为要映射的字段指定类的属性。索引器不是成员属性,这就是为什么您会收到该错误的原因。

解:

您可以执行以下操作:

var record = csv.GetRecord<dynamic>();
Run Code Online (Sandbox Code Playgroud)

您可以将其用作动态对象。

所需的解决方案

在内部,它使用ExpandoObject,因此您可以执行此操作。

var dict = csv.GetRecord<dynamic>() as IDictionary<string, object>;
Run Code Online (Sandbox Code Playgroud)