首页 > 解决方案 > 想知道我将列表添加到另一个累积列表的方式是否是最有效的方式

问题描述

我有 2 个列表(Person 和 PersonMeta)。我从一些 Api 获取 peopleList 的数据,然后将其添加到 personMetaList (其中 PersonMeta 从 Person 继承)。我正在使用 AutoMapper 来映射对象。

我的问题是关于我将 peopleList 累积添加到 peopleMetaList (最后一行代码)的方式。这是将列表添加到另一个列表的最佳方式/有效方式吗?

class Person
{
  int id {get;set;}
  string name {get;set;}
}

class PersonMeta : Person
{
  string metaProperty1 {get;set;} 
}

List<PersonMeta> peopleMetaList = new List<PersonMeta>();

List<Person> peopleList = getFromApiSomehow();

peopleList.ForEach(x => listPeopleMeta.Add(Mapper.Map<PersonMeta>(x)));

标签: c#automapper

解决方案


在我看来,更好的方法是创建自己的自定义地图。不要遍历集合,映射每个值。Automapper 为您做到这一点。

请在此处阅读有关如何使用 ConvertUsing() 函数的文档

http://docs.automapper.org/en/stable/Custom-type-converters.html

您唯一需要做的就是实现一个 TypeConverter 并在您的自动映射器配置中指定它


推荐阅读