17

I am using CsvHelper to generate a csv file based on a List, but I would like to avoid writing one of the values. As per the documentation, I used a CsvClassMap to specify the field that I want to ignore. However, the value is still being written to the file.

Here is my class:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
}

Here is my CsvClassMap:

public sealed class PersonClassMap : CsvClassMap<Person>
{
    public PersonClassMap()
    {
        Map(m => m.Id).Index(0).Name("Id");
        Map(m => m.FirstName).Index(1).Name("First Name");
        Map(m => m.LastName).Index(2).Name("Last Name");

        Map(m => m.MiddleName).Ignore();
    }
}

And this is the code that I am using to generate the output:

var persons = new List<Person>
{
    new Person {Id = 1, FirstName = "Randall", MiddleName = "Michael", LastName = "Perry"},
    new Person {Id = 2, FirstName = "Marigold", MiddleName = "Joanne", LastName = "Mercibar"},
    new Person {Id = 3, FirstName = "Sven", MiddleName = "Ergenfein", LastName = "Olafsson"}
};

using (var csvWriter = new CsvWriter(textWriter))
{
    csvWriter.WriteRecords(persons);
    textWriter.Flush();
}

My output is as follows:

Id,FirstName,MiddleName,LastName
1,Randall,Michael,Perry
2,Marigold,Joanne,Mercibar
3,Sven,Ergenfein,Olafsson

How can I get it to stop writing the MiddleName?

4

2 回答 2

22

类映射必须在运行时注册CsvHelper才能知道使用它:

using (var csvWriter = new CsvWriter(textWriter))
{
    csvWriter.Configuration.RegisterClassMap<PersonClassMap>();
    csvWriter.WriteRecords(persons);
    textWriter.Flush();
}

另请注意,在当前版本中,您无需显式忽略类映射中的字段(尽管将来会更改):

忽视

目前不使用此功能。映射只会映射您指定的属性。将来会有一个在类映射中自动映射的选项,并且任何明确声明的映射都将覆盖自动映射的映射。发生这种情况时,ignore 将用于忽略自动映射的属性。

考虑到这一点,您还可以像这样简化您的类映射:

public sealed class PersonClassMap : CsvClassMap<Person>
{
    public PersonClassMap()
    {
        Map(m => m.Id).Index(0).Name("Id");
        Map(m => m.FirstName).Index(1).Name("First Name");
        Map(m => m.LastName).Index(2).Name("Last Name");
    }
}
于 2014-11-04T15:44:39.323 回答
13

您可以使用此标签:[Ignore]

举个例子 :

//Ignored value
[Ignore]
double value0 = 0;

//Serializable value
[Name("value 1")]
double value1 = 0;
于 2019-08-14T16:08:58.930 回答