Click here to Skip to main content
15,892,005 members
Articles / Programming Languages / C#

Improving LINQ Code Reusability: Select Method

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
27 Nov 2012CPOL3 min read 9.9K   41   8  
A simple approach that will allow you to reuse the code used in the Select method
namespace Mapper
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;
	using DataContracts;
	using Domain;


	/// <summary>
	/// Ojbect mapper
	/// </summary>
	public class ObjectMapper : IObjectMapper
	{
		private Dictionary<Type, Func<object, object>> Mappers = new Dictionary<Type, Func<object, object>>
		{
			{ typeof(Tuple<Album, AlbumDetail>), CreateAlbumDetail },
			{ typeof(Tuple<Album, AlbumSummary>), CreateAlbumSummary }

			// more mappings here
			// ....
		};


		/// <summary>
		/// Converts an object of type <c>TSource</c> to an object
		/// of type <c>TDestination</c>
		/// </summary>
		/// <typeparam name="TSource">The type of the source.</typeparam>
		/// <typeparam name="TDestination">The type of the destination.</typeparam>
		/// <param name="source">The source object to convert.</param>
		/// <returns>
		/// The converted object
		/// </returns>
		public TDestination Map<TSource, TDestination>(TSource source)
		{
			if(source == null)
				return default(TDestination);

			Func<object, object> mapper = null;
			Type key = typeof(Tuple<TSource, TDestination>);

			if(Mappers.TryGetValue(key, out mapper))
			{
				var newObject = mapper(source);
				return (TDestination) newObject;
			}

			string errorMessage = string.Format("Could not find mapping for requested types (Source: {0}, Destination: {1})",
											typeof(TSource).FullName, typeof(TDestination).FullName);
			
			throw new InvalidOperationException(errorMessage);
		}


		private static object CreateAlbumDetail(object source)
		{
			var album = source as Album;

			return new AlbumDetail {
				AlbumId = album.AlbumId,
				Price = album.Price,
				Title = album.Title,

				ArtistId = album.ArtistId,
				GenreId = album.GenreId,
				ArtistName = (album.Artist == null) ? null : album.Artist.Name,
				GenreName = (album.Genre == null) ? null : album.Genre.Name
			};
		}

		private static object CreateAlbumSummary(object source)
		{
			var album = source as Album;

			return new AlbumSummary {
				AlbumId = album.AlbumId,
				Title = album.Title,
				
				ArtistName = (album.Artist == null) ? null : album.Artist.Name
			};
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Italy Italy
My name is Rui Jarimba and I was born in Madeira island, Portugal and I currently live in Rome, Italy.

I have more than 10 years of experience developing software using the .NET Framework and other technologies (Web development, Databases, ...).

Some of my professional interests are: software development best practices, software architecture, cloud computing, Continuous Integration (CI), Continuous Delivery (CD) and agile methodologies such as Scrum, Kanban, Lean and any other methodology that can help me to become a better and more productive software engineer.

I believe in good code - code that is readable, maintainable, reusable, testable and deployable. This means that I'm not the "quick and dirty" type, I write code for the medium/long term whenever possible.

Something else about me - I love music, I am an amateur photographer, not a big fan of gyms (I prefer to do some outdoor activity such as walking/hiking), big foodie (I love Mediterranean cuisine and my glass of wine!).

Comments and Discussions