LINQ Sorting Examples

So what happens when you need to sort the data from a query? The orderby, ascending, or descending keywords come into play. I’ll also be showing how to create LINQ lambda queries to perform the same tasks as a comprehension LINQ query.

SortingSolution SortingProgram

 

Program.cs Code Contents

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

namespace MyLinq
{
    class Program
    {
        ///
<summary>
        /// This is an example of some simple sorting with a comprehension query and a lambda query.
        /// </summary>

        /// <param name="args"></param>
        static void Main(string[] args)
        {
            sortWithComprehensioQuery();
            sortWithLambdaQuery();

            Console.ReadLine();
        }

        // Private Methods
        //
        private static void sortWithComprehensioQuery()
        {
            var employeeRepository = new EmployeeRepo();
            var departmentRepository = new DepartmentRepo();

            // Creating a comprehension query to sort all of the employee's.
            // Notice the sort order is ascending
            var employeeQuery =
                from employee in employeeRepository.GetAll()
                orderby employee.Name ascending
                select employee;

            // Creating a comprehension query to sort all of the departments.
            // Notice the sort order is descending.
            var departmentQuery =
                from department in departmentRepository.GetAll()
                orderby department.Name descending
                select department;

            // Outputting the comprehension query results to the console window.
            Console.WriteLine("****Displaying The Comprehension Query Sorted Employees");
            writeResults(employeeQuery);

            Console.WriteLine("****Displaying The Comprehension Sorted Departments****");
            writeResults(departmentQuery);
        }

        private static void sortWithLambdaQuery()
        {
            var employeeRepository = new EmployeeRepo();
            var departmentRepository = new DepartmentRepo();

            // Creating a lambda query to sort all of the employees.
            var employeeQuery = employeeRepository.GetAll().OrderBy(e => e.ID).ThenByDescending(e => e.Name);

            // Creating a lambda query to sort all of the departments.
            var departmentQuery = departmentRepository.GetAll().OrderBy(d => d.ID).ThenByDescending(d => d.Name);

            // Displaying the lambda query results to the console window.
            Console.WriteLine("****Displaying The Lambda Query Sorted Employees****");
            writeResults(employeeQuery);

            Console.WriteLine("****Displaying The Lambda Query Sorted Departments****");
            writeResults(departmentQuery);
        }

        private static void writeResults(IOrderedEnumerable<Department> departmentQuery)
        {
            foreach (var department in departmentQuery)
            {
                Console.WriteLine(department.Name);
            }
            Console.WriteLine();
        }

        private static void writeResults(IOrderedEnumerable<Employee> employeeQuery)
        {
            foreach (var employee in employeeQuery)
            {
                Console.WriteLine(employee.Name);
            }
            Console.WriteLine();
        }
    }
}

As with the previous example the repository classes haven’t changed. I’m still utilizing the GetAll methods to pull the data to memory.

I’m splitting the comprehension query and lambda queries into two methods. As you can see in the comprehension query method I’m utilizing the ascending and descending keywords in two queries. One query is sorting the employees names in ascending order. The other query is sorting the departments in descending order.

Upon the first look at the Lambda query you will notice that they look a lot simpler. The query is a continous string of methods. Again this depends on your own personal style as to which method if a preference. You still use the OrderBy methods to sort the data. I’m also tacking on the ThenByDescending method.

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