将列表映射到字典 [英] Mapping a list to a dictionary

查看:175
本文介绍了将列表映射到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了这堂课:

class ClassFrom
{
    public int Id { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
}

我想通过Id属性成为字典的键将其映射到其中:

I want to map it into this, with the Id property becoming the dictionary's key:

class ClassTo
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

Dictionary<int, ClassTo> toDict
    = mapper.Map<List<ClassFrom>, Dictionary<int, ClassTo>>(fromList);

是否有推荐的方法来实现这一目标?

Is there a recommended way to accomplish this?

我发现使用Automapper做到这一点的最好方法对我来说有点代码味道.我本质上是在双重映射对象,首先是ClassTo,然后是通过其构造函数到KeyValuePair:

The best way I've found to do this using Automapper has a slight code smell to me. I am essentially double-mapping the object, first to ClassTo and then to KeyValuePair through its constructor:

var cfg = new MapperConfiguration(c =>
{
    c.CreateMap<ClassFrom, ClassTo>();

    c.CreateMap<ClassFrom, KeyValuePair<int, ClassTo>>()
        .ForCtorParam("key", paramOptions => paramOptions.MapFrom(from => from.Id))
        .ForCtorParam("value", paramOptions => paramOptions.MapFrom(from => from));
});

IMapper mapper = new AutoMapper.Mapper(cfg);

List<ClassFrom> fromList = new List<ClassFrom>
{
    new ClassFrom { Id = 1, Foo = "foo1", Bar = "Bar1" },
    new ClassFrom { Id = 2, Foo = "foo2", Bar = "Bar2" }
};

Dictionary<int, ClassTo> toDict
    = mapper.Map<List<ClassFrom>, Dictionary<int, ClassTo>>(fromList);

推荐答案

您可以使用 ConstructUsing 代替 ForCtorParam .如果您按如下所示更改映射器配置,则它将正常运行.

You can use ConstructUsing instead of ForCtorParam. If you change the mapper configuration like below, it will work correctly.

var cfg = new MapperConfiguration(c =>
        {
            c.CreateMap<ClassFrom, ClassTo>();

            c.CreateMap<ClassFrom, KeyValuePair<int, ClassTo>>()
                .ConstructUsing(x => new KeyValuePair<int, ClassTo>(x.Id, new ClassTo { Bar = x.Bar, Foo = x.Foo }));
        });

这篇关于将列表映射到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆