Comma delimited string AutoMapper

I have a comma delimited string and want to map it to an object. Is this possible with automapper?

thank

+3


source to share


1 answer


Without knowing too many details, it seems to me that there are two ways to achieve this, given the following DTO we want to populate:

public class DTO 
{
    public string FirstName { get;set; }
    public string LastName { get;set; }
}

      

and sample input:



string input = "Andrew,Whitaker";

      

  • Write a custom type converter (recommended):

    public class CommaDelimitedStringConverter : TypeConverter<string, DTO>
    {
        protected override DTO ConvertCore(string source)
        {
            string[] tokens = source.Split(',');
    
            DTO result = null;
    
            if (tokens.Length == 2) 
            {        
                result = new DTO();
                result.FirstName = tokens[0];
                result.LastName = tokens[1];
            }
            return result;
        }
    }
    
    Mapper.CreateMap<string, DTO>()
        .ConvertUsing<CommaDelimitedStringConverter>();
    
          

  • Match each property to one-off (not recommended unless it's quick and dirty):

    Mapper.CreateMap<string, DTO>()
        .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.Split(',')[0]))
        .ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.Split(',')[1]));
    
          

+4


source







All Articles