Assemblers with ConvertAll

In most applications we have some kind of assembler classes, that create models used in the presentation layer:

public class EntityComboModelAssembler
{
   public List<ComboBoxModel> CreateComboBoxModels(IList<Entity> entities)
   {
      List<ComboBoxModel> list = new List<ComboBoxModel>();
      foreach (Entityentity in entities)
      {
         list.Add(new ComboBoxModel(entity, entity.Name));
      }
      return list;
   }
}

It is possible to write this code in 1 (one) line of code:

public class EntityComboModelAssembler
{
   public List<ComboBoxModel> CreateComboBoxModels(IList<Entity> entities)
   {
      return entities.AsList().ConvertAll(x => new ComboBoxModel(x, x.Name));
   }
}

We can also remove AsList method by using extension method that adds ConvertAll method to IList interface:

public static class IListExtensions
{
   public static List<TOut> ConvertAll<TIn, TOut>(this IList<TIn> source, Converter<TIn, TOut> converter)
   {
      return source.ToList().ConvertAll(converter);
   }
}

And the final code:

public class EntityComboModelAssembler
{
   public List<ComboBoxModel> CreateComboBoxModels(IList<Entity> entities)
   {
      return entities.ConvertAll(x => new ComboBoxModel(x, x.Name));
   }
}

Tags:

2 Responses to “Assemblers with ConvertAll”

  1. Marcin Obel Says:

    I have a feeling that I have seen this code somewhere before ;)

  2. Pawel Lesnikowski Says:

    In too many places ;)
    Think I’ve seen an AutoAssembler somewhere on the net…

Leave a Reply