Anonymous Type Conversions

TypeConversionsSolution TypeConversionsProgram

 

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 converting anonymous type query data without having to use a foreach loop
        /// into another data type.
        /// </summary>
        /// <param name="args"></param>
        /// 
        static void Main(string[] args)
        {
            executeDatabaseConversion();

            Console.ReadLine();
        }

        //Private Methods
        //
        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);
            }

            // Queries that keep from having to perform a separate foreach loop to convert into a strong type.
            // I just need a loop to add the objects to the collections.
            var databaseGreedyCompQuery = (from m in movieReviewsContext.Movies
                                          join r in movieReviewsContext.Reviews on m.MovieID equals r.MovieID
                                          select new MovieObject(m.MovieID, m.Title, m.ReleaseDate, r.ReviewID, r.Summary, r.Rating)).ToList();

            var databaseGreedyQuery = movieReviewsContext.Movies.Join(movieReviewsContext.Reviews, m => m.MovieID, r => r.ReviewID,
                                                        (m, r) => new MovieObject(m.MovieID, m.Title, m.ReleaseDate, r.ReviewID, r.Summary, r.Rating)).ToList();

            var greedyCompRepo = new MovieObjectRepo();
            foreach (var movieObject in databaseGreedyCompQuery)
            {
                greedyCompRepo.AddMovieObjectToList(movieObject);
                greedyCompRepo.AddMovieObjectToDictionary(movieObject.MovieID, movieObject);
            }

            var greedyQueryRepo = new MovieObjectRepo();
            foreach (var movieObject in databaseGreedyQuery)
            {
                greedyQueryRepo.AddMovieObjectToList(movieObject);
                greedyQueryRepo.AddMovieObjectToDictionary(movieObject.MovieID, movieObject);
            }

            // Write methods to display the results of the greedy variables.
            Console.WriteLine("****Displaying The Greedy Movie Dictionary List****");
            WriteResults.Write(movieObjectRepo.MovieObjectDictionary);

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

In my last post I mentioned that I was playing around with converting an anonymous type from a query in a simpler way. Here’s one way I found. The one drawback is I’m losing the deferred execution nature of the query. Reason being is I’m using a ToList method to accomplish this. Still though, the more I think about it. Even at this point I’m already trying to get to the data. Does it matter if the execution is deferred at this point? I guess it would depend on your particular application. My mindset is if I’m at this point in a user interface where I’m querying the data having it deferred isn’t going to save me anything. Once I get to this point
gimme my data… 🙂

I’ve stripped out the Employee items because you can accomplish it on in-memory data the same way. I’ve chosen to concentrate on the movie database. I’ve left the deferred queries in for review if you need it. I’ve also included both comprehension and extension methods while using ToList. You will notice that instead of creating an anonymous type I’m declaring a string MovieObject type with the required properties the class
constructor requires.

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.. 🙂

Continue reading

More Examples Of Join Operations

I went a little nuts on this simple console program. I wanted to demonstrate different ways to use the Join operator with in-memory objects from a collection and pulling information from a database. In the process of wanting to leverage anonymous types in the query I was playing around with different ways to display the data. Do I just iterate thru the query and display it. Or do I take that data, create objects, and populate another collection type with the data. Again, your personal preference might be different. I was just playing around with what ways would work.

I broke the code up into different repositories for the in-memory data and database data. I also created a WriteResults method in an attempt to use a central class to display data. I know lots of work for a simple console program. However I think it shows some cool core concepts with LINQ queries.

You will notice that the one common class that’s the same from other examples is the Employee and Department classes along with their respective repository classes. I’ve added a couple more for the database data which I’ll go over below.

Continue reading

Queries Using TypeOf

This is something I’ve run across now and then. In some cases you may find someone who decides to stick a bunch of different types in a collection. Now I’m a big proponent of using strongly types object, collections, etc… However I know not everyone does that. Or there might be a situation where it didn’t happen that way. Here’s one of many ways that you can use a LINQ query to extract different kinds of data from an abstract collection.

Continue reading