Search code examples
c#linqreflectioncsvhelper

Iterate through class properties using an action?


I'm using CsvHelper to import csv files, and in order to do so I use a mapping class as follows:

private class MyClassMap : ClassMap<MyClass>
{
    public MyClassMap ()
    {
        Map(m => m.Number).Name("Number");
        Map(m => m.Name).Name("Name");
    }
}

Most classes contain many more properties. So what I first did is create an Attribute class and added the attribute to all public properties. So I can change the mapping code:

private class MyClassMap : ClassMap<MyClass>
{
    public MyClassMap ()
    {
        var properties = typeof(MyClass).GetProperties();
        foreach (var property in properties)
        {
            var attr = property.GetCustomAttributes(typeof(HeaderAttribute), false).FirstOrDefault();
            if (attr != null)
            {
               //Here what?
            }
        }
    }
}

Also, I will make the above ctor code an extension method.

How would I use the Map() method in this case?


Solution

  • Assuming your HeaderAttribute accepts a Header as a parameter and exposes it over Header property :

        foreach (var property in properties)
        {
            var attr = property.GetCustomAttributes(typeof(HeaderAttribute), false).FirstOrDefault() as HeaderAttribute;
            if (attr != null)
            {
               //Here we use the Map method overload that takes a Type and a MemberInfo
    
                this.Map(typeof(MyClass), property).Name(attr.Header);
            }
        }