Mapping to a Dictionary

后端 未结 2 718
我在风中等你
我在风中等你 2021-01-20 11:30

I was trying to map a csv file so that each record would simply be a Dictionary.

I am receiving an

Argument

2条回答
  •  清歌不尽
    2021-01-20 12:16

    I was trying to do similar (although not reading all the columns into the Dictionary, just some). So, in case this is of use, (and strongly aided by this answer) you can have a Dictionary as a property of a class and then populate that (as Josh say's you can't populate a Dictionary on it's own as CsvHelper is expecting a member property to map to).

    The below would map to a property DictionaryProperty which is a Dictionary of the class MyClassWithDictionaryMapper.

    public class MyClassWithDictionaryMapper: ClassMap
    {
        public MyClassWithDictionaryMapper(List headers)
        {
    
            Map(m => m.DictionaryProperty).ConvertUsing
               (row => headers.Select
                (column => new { column, value = row.GetField(column) })
                .ToDictionary(d => d.column, d => d.value)
                );
        }
    }
    

提交回复
热议问题