LINQ Grouping Examples

Grouping is another powerful tool in the LINQ library. This gives you the ability to group data in specific ways. Take a look at the example by clicking more below.

GroupingSolution GroupingProgram

 

EmployeeRepo.cs Code Contents

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

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

        // Private Items
        //

        // Creating a simple in memory list of employees.
        List<Employee> _employees = new List<Employee>
        {
            new Employee() { ID = 1, Name = "Daniel", DepartmentID = 1},
            new Employee() { ID = 2, Name = "Sara", DepartmentID = 3},
            new Employee() { ID = 3, Name = "John", DepartmentID = 4},
            new Employee() { ID = 4, Name = "Debbie", DepartmentID = 2},
            new Employee() { ID = 5, Name = "Scott", DepartmentID = 1},
            new Employee() { ID = 6, Name = "Michelle", DepartmentID = 3},
            new Employee() { ID = 7, Name = "Sia", DepartmentID = 3}
        };
    }
}

For some of the examples moving forward I’ve added a repository class that will generate some in-memory data for me. In this case some sample employee data. What I’m doing is creating a private list of employees that hold employee objects, and to get that list you will need to call on the GetAll method. Why am I doing this? Well I’m working in some program layer concepts into my examples. Yes while the programs are just simple console applications it’s still a good idea to work on core programming concepts. So you will see more of this moving forward as needed.
Program.cs Code Contents

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

namespace MyLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            useGrouping();

            Console.ReadLine();
        }

        // Private Methods
        //
        private static void useGrouping()
        {
            var repository = new EmployeeRepo();

            // Demonstrating some simple uses of grouping on a LINQ comprehension query.
            var groupedEmployeesByName =
                from employee in repository.GetAll()
                group employee by employee.Name[0] into letterGroup     // Doing a group by the first letter of the employee name.    
                orderby letterGroup.Key descending
                select letterGroup;
            Write(groupedEmployeesByName, "****Grouping By Employee Name****");

            var groupedEmployeesByDepartment =
                from employee in repository.GetAll()
                where employee.DepartmentID < 3                                 // Getting all the department ID's under 3.
                group employee by employee.DepartmentID into departmentGroup    // Doing a group by the department ID.
                orderby departmentGroup.Key descending
                select departmentGroup;
            Write(groupedEmployeesByDepartment, "****Grouping By Department ID****");
        }

        // Write methods used for the grouping examples.
        private static void Write(IOrderedEnumerable<IGrouping<char, Employee>> groupedEmployees, string displayTitle)
        {
            Console.WriteLine(displayTitle);
            foreach (var group in groupedEmployees)
            {
                Console.WriteLine("Category: {0}",group.Key);
                foreach (var employee in group)
                {
                    Console.WriteLine("{0}", employee.Name);
                }
                Console.WriteLine();
            }
        }

        private static void Write(IOrderedEnumerable<IGrouping<int, Employee>> groupedEmployeesByDepartment, string displayTitle)
        {
            Console.WriteLine(displayTitle);
            foreach (var group in groupedEmployeesByDepartment)
            {
                Console.WriteLine("Department ID: {0}", group.Key);
                foreach (var employee in group)
                {
                    Console.WriteLine("{0}", employee.Name);
                }
                Console.WriteLine();
            }
        }
    }
}

What I’m doing here is creating two queries. One will group the employees by the first letter of their name. The other will group the employees by their department ID. I’m using comprehension queries for both of these. Then I’ve created a Write method that’s been overloaded with two different signature types to display the information from the queries. I’m using the GetAll method from the EmployeeRepo to gather the in-memory data needed for these queries to work. The “into” keyword is used to group the data from the query. I’m also doing an extra items by using the orderby and descending keywords.

The Write helper methods are examples that could be used in a seperate class to handle these duties if needed. Stay tuned for another example next week. 🙂

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