Anonymous Type Conversions

LINQ query anonymous type conversions can get a bit tricky at times. I’ve decided to tackle a few ways in this example. I’ll be showing you a couple demonstrations on in-memory objects and getting data from a database. With these two ways I’ll be adding the converted objects to Lists<T> and Dictionary<T> collections. I’m working on a couple of other scenarios to accomplish this. However this example is what I’ve come up with so far. So in this case this solution is getting posted.. 🙂

TypeConversionsSolution TypeConversionsProgram

 

MovieObjectRepo.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyLinq
{
    ///
<summary>
    /// Class used as a repository for Movie objects.
    /// </summary>

    public class MovieObjectRepo
    {
        // Public Read-Only Properties
        //
        public List<MovieObject> MovieObjectList { get; private set; }
        public Dictionary<int, MovieObject> MovieObjectDictionary { get; private set; }

        // Constructors
        //
        public MovieObjectRepo()
        {
            MovieObjectList = new List<MovieObject>();
            MovieObjectDictionary = new Dictionary<int, MovieObject>();
        }

        // Public Methods
        //
        public void AddMovieObjectToList(MovieObject movieObject)
        {
            MovieObjectList.Add(movieObject);
        }

        public void AddMovieObjectToDictionary(int id, MovieObject movieObject)
        {
            MovieObjectDictionary.Add(id, movieObject);
        }
    }
}

For the database object conversions I’ve created a repo class with List and a Dictionary<int, MovieObject>. Why two collections? I wanted to show how you could save the objects to two different types of collections. You can see that when the class is instantiated the collections are created. And the two Add methods become available to add the objects to their respective collections.
EmployeeObjectRepo.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyLinq
{
    ///
<summary>
    /// Class used as a repository for employee objects.
    /// </summary>

    public class EmployeeRepo
    {
        // Public Read-Only Properties
        //
        public List<Employee> EmployeeList { get; private set; }
        public Dictionary<int, Employee> EmployeeDictionary { get; private set; }

        // Constructors
        //
        public EmployeeRepo ()
        {
            EmployeeList = new List<Employee>();
            EmployeeDictionary = new Dictionary<int, Employee>();
        }

        // Public Methods
        //
        // Method that returns the private employee list collection.
        public IEnumerable<Employee> GetAll()
        {
            return _employees;
        }

        // Method used to add employee objects to the list.
        public void AddToEmployeeList(Employee employee)
        {
            EmployeeList.Add(employee);
        }

        // Method used to add employee objects to the dictionary.
        public  void AddToEmployeeDictionary(int id, Employee employee)
        {
            EmployeeDictionary.Add(id, employee);
        }

        // Private Methods
        //
        // Creating a simple in memory list of employees.
        List<Employee> _employees = new List<Employee>
        {
            new Employee(1, "Daniel", 1, new DateTime(2009, 12, 22)),
            new Employee(2, "Sara", 2, new DateTime(2012, 3, 12)),
            new Employee(3, "John", 4, new DateTime(2010, 5, 10)),
            new Employee(4, "Debbie", 2, new DateTime(2005, 1, 28)),
            new Employee(5, "Poonam", 2, new DateTime(2002, 2, 22)),
            new Employee(6, "Jack", 3, new DateTime(2001, 6, 13)),
            new Employee(7, "Ben", 4, new DateTime(2015, 5, 2)),
            new Employee(4, "Debbie", 2, new DateTime(2005, 1, 28)),
            new Employee(5, "Poonam", 2, new DateTime(2002, 2, 22)),
            new Employee(6, "Jack", 3, new DateTime(2001, 6, 13))
        };
    }
}

This class is pretty much the same with the addition of the collection classes, similar to the MovieObjectRepo class. And the methods used to add objects to the two collection types.
WriteResults.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyLinq
{
    public static class WriteResults
    {
        // Public Static Methods
        //
        public static void Write(List<Employee> list)
        {
            foreach (var employee in list)
            {
                Console.WriteLine("Name: {0} \nDepartment: {1}\n", employee.Name, employee.DepartmentName);
            }
            Console.WriteLine();
        }

        public static void Write(Dictionary<int, Employee> dictionary)
        {
            foreach (var key in dictionary)
            {
                Console.WriteLine("Name: {0} \nDepartment: {1}\n", key.Value.Name, key.Value.DepartmentName);
            }
        }

        public static void Write(List<MovieObject> list)
        {
            foreach (var movie in list)
            {
                Console.WriteLine("Movie: {0} \nSummary: {1}\n", movie.MovieTitle, movie.MovieSummary);
            }
            Console.WriteLine();
        }

        public static void Write(Dictionary<int, MovieObject> dictionary)
        {
            foreach (var key in dictionary)
            {
                Console.WriteLine("Movie: {0} \nSummary: {1}\n", key.Value.MovieTitle, key.Value.MovieSummary);
            }
            Console.WriteLine();
        }
    }
}

This class still take care of writing out results to the screen. You can see I’ve got extension methods for the different collection types and their respective object types.
Program.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Xml.Linq;
using System.Diagnostics;
using System.Collections;

namespace MyLinq
{
    class Program
    {
        ///
<summary>
        /// Demonstrating examples of conversion methods of data.
        /// </summary>

        /// <param name="args"></param>

        static void Main(string[] args)
        {
            executeInMemoryConversion();
            executeDatabaseConversion();

            Console.ReadLine();
        }

        //Private Methods
        //
        private static void executeInMemoryConversion()
        {
            // Creating the repository objects to work with.
            var employeeRepo = new EmployeeRepo();
            var departmentRepo = new DepartmentRepo();

            // Comprehension query showing how to join in memory data and create an anonymous type.
            var inMemoryComprehensionQuery = (from d in departmentRepo.GetAll()
                                             join e in employeeRepo.GetAll() on d.ID equals e.DepartmentID
                                             select new { 
                                                          EmployeeID = e.ID,
                                                          EmployeeName = e.Name,
                                                          DepartmentID = d.ID,
                                                          DepartmentName = d.Name,
                                                          EmployeeHireDate = e.HireDate
                                                        }).Distinct();

            // Query that joins the department data to the employee data, creates an anonymous type, and removes any duplicate data.
            var inMemoryAnonymousTypeQuery = departmentRepo.GetAll().Join(employeeRepo.GetAll(), departmentID => departmentID.ID, employeeID => employeeID.DepartmentID,
                                                        (d, e) => new { 
                                                                        EmployeeID = e.ID, 
                                                                        EmployeeName = e.Name, 
                                                                        DepartmentID = d.ID, 
                                                                        DepartmentName = d.Name, 
                                                                        EmployeeHireDate = e.HireDate 
                                                                      }).Distinct();

            // Taking the anonymous type collection from the query, creating the Employee object properties, and adding it to the List and Dictionary collections.
            foreach (var employeeObject in inMemoryAnonymousTypeQuery)
            {
                var employee = new Employee(employeeObject.EmployeeID, 
                                            employeeObject.EmployeeName, 
                                            employeeObject.DepartmentID, 
                                            employeeObject.DepartmentName, 
                                            employeeObject.EmployeeHireDate);

                employeeRepo.AddToEmployeeList(employee);
                employeeRepo.AddToEmployeeDictionary(employee.ID, employee);
            }

            // Displaying the query results for the List and Dictionary collections.
            Console.WriteLine("****Displaying The Employee List****");
            WriteResults.Write(employeeRepo.EmployeeList);

            Console.WriteLine("****Displaying The Employee Dictionary List****");
            WriteResults.Write(employeeRepo.EmployeeDictionary);
        }

        private static void executeDatabaseConversion()
        {
            // Creating the repository objects to work with.
            MovieReviewsDataContext movieReviewsContext = new MovieReviewsDataContext();
            MovieObjectRepo movieObjectRepo = new MovieObjectRepo();

            // Comprehension query showing how to join database data and create an anonymous type.
            var databaseComprehensionQuery = from m in movieReviewsContext.Movies
                                             join r in movieReviewsContext.Reviews on m.MovieID equals r.MovieID
                                             select new {
                                                           MovieID = m.MovieID,
                                                           MovieTitle = m.Title,
                                                           ReleaseDate = m.ReleaseDate,
                                                           ReviewID = r.ReviewID,
                                                           MovieSummary = r.Summary,
                                                           MovieRating = r.Rating
                                                        };

            // Query that joins the movie table to the reviews table and creates an anonymous type.
            var databaseAnonymousTypeQuery = movieReviewsContext.Movies.Join(movieReviewsContext.Reviews, m => m.MovieID, r => r.ReviewID,
                                                                    (m, r) => new {
                                                                                    MovieID = m.MovieID,
                                                                                    MovieTitle = m.Title,
                                                                                    ReleaseDate = m.ReleaseDate,
                                                                                    ReviewID = r.ReviewID,
                                                                                    MovieSummery = r.Summary,
                                                                                    MovieRating = r.Rating
                                                                                  });

            // Taking the anonymous type collection from the query, creating the MovieObject object properties, and adding it to the
            // List and Dictionary collections.
            foreach (var movieObject in databaseAnonymousTypeQuery)
            {
                var movie = new MovieObject(movieObject.MovieID,
                                            movieObject.MovieTitle,
                                            movieObject.ReleaseDate,
                                            movieObject.ReviewID,
                                            movieObject.MovieSummery,
                                            movieObject.MovieRating);

                movieObjectRepo.AddMovieObjectToList(movie);
                movieObjectRepo.AddMovieObjectToDictionary(movie.MovieID, movie);
            }

            // Displaying the query results for the List and Dictionary collections.
            Console.WriteLine("****Displaying The Movie List****");
            WriteResults.Write(movieObjectRepo.MovieObjectList);

            Console.WriteLine("****Displaying The Movie Dictionary List****");
            WriteResults.Write(movieObjectRepo.MovieObjectDictionary);
        }
    }
}

The biggest take away from seeing all this is how I’m using the LINQ queries, both query and extension methods, converting the data from the query into an object type, and adding those objects to their respective collections. I’m using a foreach loop to iterate thru the query results, creating a strongly types object and its properties, and adding it the collections. This is being done in both the in-memory objects and the database objects.

I’m sure there’s a simpler way of going about this that I haven’t figured out yet. There almost always is as I learn these type of things. Like I said earlier. I’m working on something. Once I get it figured out I’ll post it.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s