Select method is used to project each element of a sequence into a new form, i.e. it can be used to map a collection of one type to a collection of another type. In this article I’ll show you a simple approach that will allow you to reuse the code used in the Select method.

Solution 2 – Creating a generic ObjectMapper object

The previous solution solves the code reusability problem, but there’s still a tight coupling between components. Abstractions should be used to implement loose coupling between components – in this case, to abstract the mapping code.

Step 1: define a contract (interface) with a method that converts one object of type TSource to an object of type TDestination:

Final thoughts

In this article you learned how to reuse the code used in the Select method, and how you can use that code to map single objects. But writing mapping code is tedious and time consuming. There are mapping tools out there that can make your life easier – AutoMapper is one of them. I’ve used it in the past and I definitely recommend it. So, why use Automapper? Quoting their website:

“What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types”

“Mapping code is boring. Testing mapping code is even more boring. AutoMapper provides simple configuration of types, as well as simple testing of mappings”