Examples Of LINQ Query Syntax

For this example I’m going to be showing some different ways to LINQ query syntax on a database and some in-memory objects. I’ll be showing the two main different types of queries. Extension and method syntax.

In the coming posts you will see me add a little more complexity. Why for such a simple console program? Well it can just show some basic concepts that can be used in larger, more user friendly programs.

QuerySyntaxSolution QuerySyntaxProgram

 

 
Employee.cs Code Contents

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

namespace MyLinq
{
    public class Employee
    {
        // Public Properties
        public int ID { get; set; }
        public string Name { get; set; }
        public DateTime HireDate { get; set; }
    }
}

The Employee class is a really really simple class. It just has some public properties used to identify the ID, Name, and HireDate.

 
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;

namespace MyLinq
{
    class Program
    {
        /// <summary>
        /// Demonstrating an examples of using comprehension and extension methods when using LINQ queries.
        /// </summary>
        /// <param name="args"></param>

        static void Main(string[] args)
        {
            comprehensionQuerySyntax();
            extensionMethodSyntax();

            Console.ReadLine();
        }

        //Private Methods
        //
        private static void comprehensionQuerySyntax()
        {
            Console.WriteLine("****Running Comprehension Query On A Database****");

            // The data context used to connect and pull information from the database.
            MovieReviewsDataContext movieReviewsContext = new MovieReviewsDataContext();

            // LINQ query to get the top rated movies after a certain released year.
            IEnumerable<Movie> queryOne =
                from r in movieReviewsContext.Movies
                where r.ReleaseDate > 1980
                orderby r.Reviews.Average(rating => rating.Rating) descending       // Able to pull the review rating because of the DB association in the dbml.
                select r;

            // Iterate thru the IEnumerable to display the data from the LINQ query.
            foreach (Movie movie in queryOne)
            {
                Console.WriteLine(movie.Title);
            }
            Console.WriteLine();

            // Demonstrating a comprehension query on an in-memory object.
            Console.WriteLine("****Running Comprehension Query On An In Memory Object");

            // Creating a object to hold in memory.
            var employees = createEmployeeArray();

            // Using a LINQ query on the memory object.
            var date = new DateTime(2011, 1, 1);
            IEnumerable<Employee> queryTwo =
                (from e in employees
                 where e.HireDate < date
                 orderby e.ID ascending
                 select e);

            // Displaying the queried data.
            foreach (var item in queryTwo)
            {
                Console.WriteLine(item.Name);
            }
            Console.WriteLine();
        }

        private static void extensionMethodSyntax()
        {
            // Demonstrating extension method syntax on a database object.
            Console.WriteLine("****Running A LINQ Extension Method On A Database");

            // Creating the database connection and creating a LINQ query against the database.
            MovieReviewsDataContext movieContext = new MovieReviewsDataContext();
            IEnumerable<Movie> queryOne = movieContext.Movies.Where(m => m.ReleaseDate > 1980);

            // Display the results from the query.
            foreach (var item in queryOne)
            {
                Console.WriteLine(item.Title);
            }
            Console.WriteLine();

            // Demonstrating extension method syntax on an in memory object.
            Console.WriteLine("****Running A LINQ Extension Method On An In Memory Object.");
            var date = new DateTime(2011, 1, 1);

            // Creating an in memory object and creating a LINQ query against the memory object.
            var employees = createEmployeeArray();
            IEnumerable<Employee> queryTwo = employees.Where(e => e.HireDate < date);

            // Displaying the results from the query.
            foreach (var item in queryTwo)
            {
                Console.WriteLine(item.Name);
            }
            Console.WriteLine();
        }

        private static Employee[] createEmployeeArray()
        {
            Employee[] employees = new Employee[]
            {
                new Employee { ID = 1, Name = "Daniel", HireDate = new DateTime(2015, 10, 15) },
                new Employee { ID = 2, Name = "Jeff", HireDate = new DateTime(2010, 12, 10) },
                new Employee { ID = 3, Name = "Sara", HireDate = new DateTime(2001, 1, 22) },
                new Employee { ID = 4, Name = "Mike", HireDate = new DateTime(2011, 4, 12)}
            };
            return employees;
        }
    }
}

Here you will see the program executing two main methods. One is executing commands for Extension, or comprehension, query syntax. In the coming posts you will me refer to Extension method queries as comprehension queries. This comes from a teacher of mine. Basically they both mean the same thing. And the other method is using LINQ method syntax. I’ll be providing two examples with these queries showing to pull information from an in-memory object along with a database. The database is a simple database modeled in .NET dbml. Both ways provide some pretty powerful ways to look for and query data.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s