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"

Sebastian Patten
  • 7,157
  • 4
  • 45
  • 51

2 Answers2

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"
Sven Grosen
  • 5,616
  • 3
  • 30
  • 52
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 :)

ahybertz
  • 514
  • 4
  • 9