简体   繁体   中英

Convert an array of one datatype to array of another in NET core in an efficient way?

I have an array of database entities that I need to convert to some different class in order to serve as a REST request result:

DatabaseDTO[] arrayFromDb = _repo.GetAllData();
OutgoinDTO[] = convertFromDatabaseDTO (arrayFromDb);

what is the most efficient way to do so (I assume that OutgoingDTO has a constructor that takes DatabaseDTO)

you can use LINQ to map an object from another, as:

var outgoinDTO = arrayFromDb.Select(x => new OutgoinDTO() {
  outgoing_param1 = arrayFromDb.param1,
  outgoing_param2 = arrayFromDb.param2,
  outgoing_param3 = calcSum(arrayFromDb.param2, arrayFromDb.param3),
  ..
  outgoing_paramn = arrayFromDb.paramn
});

calcSum(int a, int b) {
  return a + b;
}

So, you can calculate some results for Dto parameters from your DbClass. If both classes have same parameters (DbClass and DtoClass), you can use AutoMapper, how @Adem Aygun said below

you can use AutoMapper.Collection

Mapper.Map<List<OrderDTO>,List<Order>>(orderDtos, orders);

and here this

for different members :

    Mapper.CreateMap<Employee, EmployeeDto>()
   .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));

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