c# - 想知道我将列表添加到另一个累积列表的方式是否是最有效的方式
问题描述
我有 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)));
解决方案
在我看来,更好的方法是创建自己的自定义地图。不要遍历集合,映射每个值。Automapper 为您做到这一点。
请在此处阅读有关如何使用 ConvertUsing() 函数的文档
http://docs.automapper.org/en/stable/Custom-type-converters.html
您唯一需要做的就是实现一个 TypeConverter 并在您的自动映射器配置中指定它
推荐阅读
- java - 使用 UnicastReceivingChannelAdapter 处理 UDP 以创建发布-订阅通道
- ruby-on-rails - Rails:无法打开共享对象文件:没有这样的文件或目录
- javascript - 我的 JS 没有处理 HTML 元素
- docker - 如何将来自不同服务器的卷添加到我的 docker-compose 文件中
- list - Haskell递归地将函数应用于每个元素,但首先?
- solr - 如何在同一个子文档上查询和过滤具有多个条件的 Solr 6.4 子文档?
- c++ - 为什么我收到“声明与 (x) 不兼容”?
- wcf - 如何检查发送到 iis 的证书
- c# - 为什么使用 PlayerPrefs 将 3D 对象的比例保存为黑色 2D 形状?
- wordpress - 当我尝试打开管理面板时,它被重定向到 woocommerce 设置向导