Home > Net >  Automapper and multidimensional list
Automapper and multidimensional list

Time:11-26

I want to map List<List<Item>> into List<List<Item2>> but I can't make it working. Is there a way to do it using simple configuration or does such case require writing custom converter? Here is my case (available also on dotnetfiddle):

using System;
using System.Collections.Generic;
using AutoMapper;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var configuration = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<ItemCollection, List<List<Item2>>>();
            cfg.CreateMap<List<List<Item>>, List<List<Item2>>>();
            cfg.CreateMap<List<Item>, List<Item2>>();
            cfg.CreateMap<Item, Item2>().ForMember(x => x.Name, opt => opt.MapFrom(x => x.Name));
        });
        var mapper = new Mapper(configuration);
        
        var collection = new ItemCollection();
        collection.Add(new List<Item>(){new Item{Name = "item"}});
        
        var dest = mapper.Map<List<List<Item2>>>(collection);
        Console.WriteLine(JsonConvert.SerializeObject(dest));
    }
}

public class ItemCollection : List<List<Item>>
{
}

public class Item
{
    public string Name { get; set; }
}

public class Item2
{
    public string Name { get; set; }
}

As a result I'd like to see [[{Name = "item"}]] in output window.

CodePudding user response:

You don't need to specify how to map to collections, only the individual types.

https://dotnetfiddle.net/D6HGik

  • Related