映射到字典

问题描述 投票:2回答:2

我试图映射一个csv文件,以便每个记录都只是一个Dictionary<string,object>

我收到一个

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]);
            }
        }
    } 
}
c# csvhelper
2个回答
6
投票

很遗憾,当前不支持映射到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?

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

SOLUTION:

您可以做的是这样:

var record = csv.GetRecord<dynamic>();

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

所需解决方案

内部,它使用ExpandoObject,因此您可以这样做。

var dict = csv.GetRecord<dynamic>() as IDictionary<string, object>;

0
投票

我正在尝试做类似的事情(尽管没有将所有列读到Dictionary中,只是其中一些)。因此,如果有用(在this answer的大力协助下),您可以将Dictionary作为类的属性,然后填充该类(如乔什所说,您不能在其上填充Dictionary作为CsvHelper拥有,期望成员属性可以映射到。)

下面将映射到属性DictionaryProperty,它是类Dictionary<string,string>MyClassWithDictionaryMapper

public class MyClassWithDictionaryMapper: ClassMap<MyClassWithDictionary>
{
    public MyClassWithDictionaryMapper(List<string> headers)
    {

        Map(m => m.DictionaryProperty).ConvertUsing
           (row => headers.Select
            (column => new { column, value = row.GetField(column) })
            .ToDictionary(d => d.column, d => d.value)
            );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.