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));
}
}
September 18th, 2013 at 13:14
I have a feeling that I have seen this code somewhere before 😉
September 18th, 2013 at 14:53
In too many places 😉
Think I’ve seen an AutoAssembler somewhere on the net…