将项目添加到新集合,而不是替换整个集合

本文关键字:集合 替换 添加 新集合 项目 | 更新日期: 2023-09-27 18:16:03

我正在使用Automapper,我想知道是否有可能将源上的集合中的所有项目添加到目标。

考虑以下内容:

public class A { public IDictionary<int, string> myDictionary = new Dictionary<int, string>(); }
public class B { public IDictionary<int, string> myDictionary = new Dictionary<int, string>(); }

然后创建映射:

Mapper.CreateMap<A, B>();

并执行实际映射:

Mapper.Map<A, B>(instanceOfA);

我相信在屏幕后面这将会发生:

newInstanceOfB.myDictionary = instanceOfA.myDictionary

但是是否有可能告诉Automapper这样做(也许使用自定义转换器…):

foreach (var item in instanceOfA.myDictionary)
    newInstanceOfB.myDictionary[item.Key] = item.Value

将项目添加到新集合,而不是替换整个集合

这似乎对我有用

Mapper.CreateMap<A, B>()
     .ForMember(d => d.myDictionary, opt => opt.ResolveUsing(
                s => s.myDictionary.ToDictionary(pair => pair.Key, pair => pair.Value)));

这是完整的示例

public class A { public IDictionary<int, string> myDictionary = new Dictionary<int, string>(); }
public class B { public IDictionary<int, string> myDictionary = new Dictionary<int, string>(); }
class Program
{
    static void Main(string[] args)
    {
        var instanceOfA = new A
                              {
                                  myDictionary = new Dictionary<int, string>
                                                     {
                                                         {1, "a"},
                                                         {2, "b"}
                                                     }
                              };
        Mapper.CreateMap<A, B>()
            .ForMember(d => d.myDictionary, opt => opt.ResolveUsing(
              s => s.myDictionary.ToDictionary(pair => pair.Key, pair => pair.Value)));
        var instanceOfB = Mapper.Map<A, B>(instanceOfA);
        instanceOfA.myDictionary[1] = "c";
        if (instanceOfB.myDictionary[1] == "c")
            Console.WriteLine("Failed");
        else
            Console.WriteLine("Succeeded");
        Console.ReadLine();
    }
}

在注释后编辑:*再次编辑*

Mapper.CreateMap<A, B>()
   .ForMember(d => d.myDictionary, opt => opt.Ignore())
   .AfterMap((s, d) =>
                      {
                       d.myDictionary.Clear();
                       s.myDictionary.ToList().ForEach(p => d.myDictionary.Add(p));
                   });