0

Given the following:

public class NameValueContainer { public string Name { get; set; } public IList<string> Values { get; set; } } var first = new NameValueContainer { Name = "First", Values = new List<string> { "Value1", "Value2" } } var second = new NameValueContainer { Name = "Second", Values = new List<string> { "Value3" } } 

Using AutoMapper, how do I merge first and second so that I am left with?:

Name: "First"

Values: "Value1", "Value2", "Value3"

2
  • 2
    Your question doesn't really make sense. AutoMapper maps from one type to another, not two instances of one type to another instance. Commented Oct 21, 2014 at 16:16
  • That's a fair point :) Commented Oct 21, 2014 at 16:23

2 Answers 2

1

As the comments point out, tying this to AutoMapper doesn't really make sense. The easiest way to do this is using Linq:

var merged = new NameValueContainer { Name = first.Name, Values = first.Values.Union(second.Values).ToList() }; //merged.Values: "Value1", "Value2", "Value3" 
Sign up to request clarification or add additional context in comments.

Comments

1

Well, I know it don't make a lot of sense, but it's possible in automapper like this.

public class NameValueMerger : ITypeConverter<IList<string>, IList<string>> { public IList<string> Convert(ResolutionContext context) { var source = context.SourceValue as IList<string>; var destination = context.DestinationValue as IList<string>; if (source != null && destination != null) { return destination.Concat(source).ToList(); } throw new ArgumentException("Types not compatible for converter."); } } public class NameValueContainer { public string Name { get; set; } public IList<string> Values { get; set; } } internal class Program { static Program() { Mapper.CreateMap<NameValueContainer, NameValueContainer>(); Mapper.CreateMap<IList<string>, IList<string>>().ConvertUsing(new NameValueMerger()); } private static void Main(string[] args) { var first = new NameValueContainer { Name = "First", Values = new List<string> { "Value1", "Value2" } }; var second = new NameValueContainer { Name = "Second", Values = new List<string> { "Value3" } }; var result = Mapper.Map(second, first); Console.Write("Value : " + string.Join(", ", result.Values)); Console.WriteLine(); } } 

The output of this will be

Value : Value1, Value2, Value3 Press any key to continue . . . 

Just saying - because you can might not mean you should :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.