I have a loop which uses AutoMapper to map two different instances of objects A
& B
into a new instance of a third object, C
. The object C
contains all the fields of A
& B
combined.
In other words, they could look like this:
class A
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class B
{
public DateTime TimeOfBirth { get; set; }
}
// A & B combined
class C
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime TimeOfBirth { get; set; }
}
Currently I have a loop which uses AutoMapper to first map A
into C
. And then map B
into the result. Like this:
List<C> output = new();
foreach (var a in listA)
{
C result = _mapper.Map<C>(a);
_mapper.Map<B, C>(listB.Single(b => b.Id == a.ForeinKey), result);
output.Add(result);
}
I would like to do this with Linq. My initial thought was to use the Zip method, but I cannot get it to work with AutoMapper. I would expect that it should look something like the below, but I cannot get it to work (it doesn't compile):
var output = _mapper.Map<C>(listA).Zip(_mapper.Map<C>(listB));
What am I missing? Is it even possible to do what I am trying - without making an even bigger mess?
CodePudding user response:
Since you want to do an in-place mapping the second time, you still need to call Map<B, C>(b, existingC)
. For that you can use the Zip
overload taking a selector fucntion:
var output = _mapper.Map<C>(listA)
.Zip(listB, (c, b) => _mapper.Map<B, C>(b, c));
CodePudding user response:
You have to use Join in such case:
var output = listA
.Join(listB, a => a.ForeinKey, b => b.Id, (a, b) =>
_mapper.Map<B, C>(_mapper.Map<C>(a))
)
.ToList();