0

I am trying to optimize this part of code:

   Mapper.CreateMap<Document, DocumentViewModel>()
        .ForMember(g => g.Id, map => map.MapFrom(d => d.documentVersion.Where(v => v.version == d.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First().Id))
        .ForMember(g => g.IdRootDocument, map => map.MapFrom(d => d.Id))
        .ForMember(g => g.certyficateType, map => map.MapFrom(d => d.documentVersion.Where(v => v.version == d.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First().certyficateType))

I'm Using automapper, and I'm trying to optimize this part of code

In this part I'm trying mapping object from document to documentViewModel, in this complex model, source data always will be latest document version:

d => d.documentVersion.Where(v => v.version == d.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First().myProportyX

Could anyone offer an example or suggestion as to how to approach optimization in this situation?

Rob G
  • 3,496
  • 1
  • 20
  • 29
michal
  • 37
  • 2
  • 7
  • any idea ? i have no idea how write this in right way... – michal Aug 19 '15 at 18:50
  • Can you provide the class structure for Document and and other related models to the mapping? – drneel Aug 19 '15 at 19:20
  • Unfortunately I can't provide the whole class. I have share small but very important part of code... – michal Aug 19 '15 at 19:26
  • Without more information, this question will likely be closed as too broad. You probably can clean up the mapping by adding a property to Document that contains the latest version and another one for latest subversion; and then modifying your linq in the mapping to use those – drneel Aug 19 '15 at 19:30

2 Answers2

0

d => d.documentVersion.Where(v => v.version == d.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First().myProporty

You are iterating quite a few times here, you may consider doing something like:

d.documentVersion.OrderByDescending(v => v.version).ThenByDescending(v => v.subVersion).First().myProperty

to reduce the number of iterations and only get the top version/subversion.

Rob G
  • 3,496
  • 1
  • 20
  • 29
0

optimization mapping:

       Mapper
            .CreateMap<Document, DocumentViewModel>()
            .ConvertUsing(doc =>
                   {
                       DocumentViewModel result = new DocumentViewModel();
                       DocumentVersion lastVersion = doc.documentVersion.Where(v => v.version == doc.documentVersion.Select(s => s.version).Max()).OrderByDescending(s => s.subVersion).First();
                       Mapper.Map(lastVersion, result);
                       return result;
                   });
michal
  • 37
  • 2
  • 7