Click here to Skip to main content
15,895,142 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 Demo
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	using Domain;
	using Mapper;
	using DataContracts;

	class Program
	{
		private static IEnumerable<Album> Albums
		{
			get
			{
				yield return new Album
				{
					AlbumId = 1,
					Price = 10.0m,
					Title = "The Dreamer",

					Artist = new Artist {
						ArtistId = 1,
						Name = "José James"
					},

					Genre = new Genre {
						GenreId = 1,
						Name = "Jazz"
					}
				};

				yield return new Album
				{
					AlbumId = 2,
					Price = 12.0m,
					Title = "Final Conversation of Kings",

					Artist = new Artist {
						ArtistId = 2,
						Name = "The Butterfly Effect"
					},

					Genre = new Genre {
						GenreId = 2,
						Name = "Progressive Rock"
					}
				};

				yield return new Album
				{
					AlbumId = 3,
					Price = 10.0m,
					Title = "Devotion",

					Artist = new Artist {
						ArtistId = 3,
						Name = "Jessie Ware"
					},

					Genre = new Genre {
						GenreId = 3,
						Name = "Pop Electronica"
					}
				};

				yield return new Album
				{
					AlbumId = 4,
					Price = 10.0m,
					Title = "Heritage",

					Artist = new Artist {
						ArtistId = 4,
						Name = "Opeth"
					},

					Genre = new Genre {
						GenreId = 4,
						Name = "Metal"
					}
				};


				yield return new Album
				{
					AlbumId = 5,
					Price = 12.0m,
					Title = "Fabriclive. 55 ",

					Artist = new Artist
					{
						ArtistId = 5,
						Name = "DJ Marky"
					},

					Genre = new Genre
					{
						GenreId = 5,
						Name = "Drum & Bass"
					}
				};
			}
		}

		static void Main(string[] args)
		{
			Console.WriteLine("Using LINQ - Convert to AlbumDetail");
			LinqConvertToAlbumDetail();
			Console.Read();


			Console.WriteLine("{0}{0}Using LINQ - Convert to AlbumSummary", System.Environment.NewLine);
			LinqConvertToAlbumSummary();
			Console.Read();


			Console.WriteLine("{0}{0}Using the mapper to create a single object - AlbumSummary", System.Environment.NewLine);
			CreateSingleObject();
			Console.Read();
		}


		private static void LinqConvertToAlbumDetail()
		{
			IObjectMapper mapper = new ObjectMapper();

			// using a delegate in Select method
			List<AlbumDetail> details = Albums.Select(mapper.Map<Album, AlbumDetail>).ToList();

			// OR
			// List<AlbumDetail> details = Albums.Select(x => mapper.Map<Album, AlbumDetail>(x));


			details.ForEach(detail => Console.WriteLine(detail));
		}


		private static void LinqConvertToAlbumSummary()
		{
			IObjectMapper mapper = new ObjectMapper();

			List <AlbumSummary> summaries = Albums.Select(mapper.Map<Album, AlbumSummary>).ToList();

			summaries.ForEach(summary => Console.WriteLine(summary));
		}


		private static void CreateSingleObject()
		{
			IObjectMapper mapper = new ObjectMapper();
			Album album = Albums.First();
			AlbumSummary summary = mapper.Map<Album, AlbumSummary>(album);

			Console.WriteLine(summary);
		}














		//private static AlbumDetail CreateAlbumDetail(Album 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 AlbumSummary CreateAlbumSummary(Album album)
		{
			return new AlbumSummary {
				AlbumId = album.AlbumId,
				Title = album.Title,

				ArtistName = (album.Artist == null) ? null : album.Artist.Name
			};
		}


		//private static void LinqConvertToAlbumDetail(int genreId)
		//{
		//    IObjectMapper mapper = new ObjectMapper();

		//    // using a delegate in Select method
		//    var albums = Albums.Select(CreateAlbumDetail);
		//    var albumsByGenre = Albums.Where(x => x.GenreId == genreId)
		//                            .Select(CreateAlbumDetail);

		//    // OR
		//    var albums2 = Albums.Select(x => CreateAlbumDetail(x));
		//    var albumsByGenre2 = Albums.Where(x => x.GenreId == genreId)
		//                            .Select(x => CreateAlbumDetail(x));
		//}
	}
}

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