2

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)

7
  • 1
    Given that you are converting between arrays, maybe Array.ConvertAll() will do the trick? This is likely to be optimally efficient. Commented Feb 26, 2020 at 11:27
  • 2
    define "efficient"; coding effort? memory usage? runtime? dependency tree? lines of code? allocations? These are all competing factors: you can't say "all of them" Commented Feb 26, 2020 at 11:33
  • Why not create a new array with the desired size and just loop? That's what Array.ConvertAll does. Do you have a specific performance issue? The conversion constructor itself is extra complexity that binds the two types together for example. Why not use a separate conversion method? Or AutoMapper? What are you looking for? Commented Feb 26, 2020 at 11:37
  • One approach is to not build the array of the "wrong" types to begin with. If you could convert them on the fly, you'd save a whole bunch of memory. See if your repository might not be amenable to a rewrite where it returns IEnumerable instead of an array. Commented Feb 26, 2020 at 11:44
  • Explicitly, DatabaseDTO[] arrayFromDb = _repo.GetAllData(); OutgoinDTO[] = Array.ConvertAll(arrayFromDb, x => new OutgoinDTO(x)); Commented Feb 26, 2020 at 11:46

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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));

1 Comment

use automapper only if almost parameters exist in both classes. if need to execute some functions to calculate params result, will be better to use linq

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.