InCode
InCode

Reputation: 503

How to use automapper from string to List of Strings

Using automapper how do we convert a string separated with spaces to a List ?

Data:

foo1 foo2 foo3 foo4

Class:

public class myFooList
{
   public int myId;
   public List<string> myListOfStrings;
}

Using automapper defaults.

Mapper.CreateMap<data,myFooList>()        
    .ForMember(d=>d.mListOfStrings, s=>s.MapFrom(s=>s.Data));

I get data in the form of one line per character.

Ex:

f
o
o
1

f
o
o
2

etc..etc..

Upvotes: 3

Views: 3571

Answers (2)

chris
chris

Reputation: 403

Mapper.CreateMap<data,myFooList>()
.ForMember(d=>d.mListOfStrings, s=>s.MapFrom(s=>s.Data.Split()));

Looks like automapper makes a reasonable assumption and enumerates the string character by character. Just be explicit about the Split.

nvoigt's suggestion is also correct - are you sure you want to use automapper?

Upvotes: 2

nvoigt
nvoigt

Reputation: 77354

It's pretty easy to split a string and create a list from it:

var text = "foo1 foo2 foo3 foo4";
var delimiters = new char [] {' '};

var myListOfStrings = text.Split(delimiters).ToList();

I've never needed AutoMapper, so you may want to work from here...

Upvotes: 2

Related Questions