Search code examples
c#automapperautomapper-2

How do you merge two objects in AutoMapper?


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"


Solution

  • 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"