C#C
C#4y ago
malkav

Generic Dto Mapper

possibly oddball question, but I'm trying to make Dto mappers, and I came across List<T> and Array<T> items in my Dto's that I needed to map by using a foreach loop for each of these items. But I was wondering if there is a way to create a generic mapper of sorts for these things?

I mean I tried starting, but I get stuck..

Currently each of these loops does the same, but with different properties in a different model class.
Here's an example of the foreach loop they do:
foreach (TargetDto item in dto.ListProperty)
{
    sourceDto.ListProperty.Add(
      new()
      {
        // each property is set here like so:
        PropertyName = item.PropertyName
      });
}  

however when I try to do this in a static helper class, I get stuck on the following:
public static ICollection<T> ComplexMapper<TS, T>(this ICollection<TS> source, ICollection<T> target)
{
    foreach (var item in target)
    {
      source.Add(
        // And now I'm stuck because I can't create 'new()' of T because it does not have a new() keyword
      );
    }
}
Was this page helpful?