简体   繁体   中英

How to create generic mapping with AutoMapper and ConstructUsing

I have a map configuration:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<IDictionary<int, MyType1>, List<MyType1>>().ConstructUsing(
        x0 => x0?.OrderBy(x => x.Key).Select(x => x.Value).ToList());
});

How can I change this to work with "all MyTypes"?

I want to convert from IDictionary<int, T> to List<T> for any T type.

I found a very ugly solution:

cfg.CreateMap(typeof(IDictionary<,>), typeof(List<>)).ConstructUsing(
    x0 =>
    {
        if (x0 == null)
        {
            return null;
        }

        var dict = (IEnumerable)x0;
        var type = x0.GetType().GetGenericArguments()[1];
        var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(type));
        CastDictionaryEntry(dict).OrderBy(x => x.Key).ForEach(x => list.Add(x.Value));
        return list;
    }
);

and:

static IEnumerable<DictionaryEntry> CastDictionaryEntry(IEnumerable dict)
{
    foreach (var item in dict)
    {
        yield return (DictionaryEntry)item;
    }
}

Is there any easier way to do this?

I think works, but then again I haven't tested against a broad set of inputs-

class ABC
    {
        public int MyProperty { get; set; }
        public int MyProperty2 { get; set; }
    }
    static List<T> ConfigureMap<T>(Dictionary<int, T> input) where T : class
    {
        AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap(input.GetType(), typeof(List<T>))
        .ConstructUsing(Construct));

        return Mapper.Map<List<T>>(input);

    }

    private static object Construct(object arg1, ResolutionContext arg2)
    {
        if (arg1 != null)
        {
            var val = arg1 as IDictionary;
            var argument = val.GetType().GetGenericArguments()[1];
            if (val != null)
            {
                var type = Activator.CreateInstance(typeof(List<>).MakeGenericType(argument));

                foreach (var key in val.Keys)
                {
                    ((IList)type).Add(val[key]);
                }

                return type;
            }
        }

        return null;
    }

var so = new Dictionary<int, ABC> { { 1, new ABC { MyProperty = 10, MyProperty2 = 30 } } };
var dest = new List<ABC>();
var res = ConfigureMap<ABC>(so);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM