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:

Questions?

Consider using our Q&A forum for asking questions.

2 Responses to “Assemblers with ConvertAll”

  1. Marcin Obel Says:

    I have a feeling that I have seen this code somewhere before 😉

  2. Limilabs support Says:

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