ISourceCode

Make the frequent cases fast and the rare case correct

Group a type with DateTime member based on the split of a year as quarterly/half yearly using C# and LINQ

In this post there is code to classify a type employee with members name and joindate into a particular quarter of a year based on their joining date.

You can run the code on linqpad or VS.

If you want to classify it on half yearly basis change GroupBy(o => (o.joindate.Month – 1) / 3) to
GroupBy(o => (o.joindate.Month – 1) / 6)

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

namespace DateFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> emp = new List<Employee>()
			{ 
				new Employee 
				{ 
					name = "Steve", joindate = DateTime.Parse("3/28/2012", System.Globalization.CultureInfo.InvariantCulture)
				},
				new Employee 
				{ 
					name = "John", joindate = DateTime.Parse("5/28/2012", System.Globalization.CultureInfo.InvariantCulture) 
				},
				new Employee 
				{ 
					name = "Chin", joindate = DateTime.Parse("12/21/2012", System.Globalization.CultureInfo.InvariantCulture) 
				},
				new Employee 
				{ 
					name = "Henry", joindate = DateTime.Parse("12/25/2012", System.Globalization.CultureInfo.InvariantCulture) 
				}
			};

            // uncomment lines below to view the dump on linqpad (pasted below)
            /*emp.
            Select(o => new Employee { name = o.name, joindate = o.joindate })
            .GroupBy(o => (o.joindate.Month - 1) / 3)
            .ToDictionary(kvp => kvp.Key, kvp => kvp.ToList()).Dump();*/

            var query = emp.
            Select(o => new Employee { name = o.name, joindate = o.joindate })
            .GroupBy(o => (o.joindate.Month - 1) / 3)
            .ToDictionary(kvp => kvp.Key, kvp => kvp.ToList());

            foreach (KeyValuePair<int, List<Employee>> kvp in query)
            {
                Console.WriteLine(kvp.Key.ToString());

                foreach (Employee employee in kvp.Value)
                {
                    Console.WriteLine(employee.name);
                }
            }

            Console.ReadKey();
        }
    }

    class Employee
    {
        public string name { get; set; }
        public DateTime joindate { get; set; }
    }
}

This is a snapshot from linqpad. The key value 0,1,2 and 3 are the quarters. This helped me get a report of employees hired on a quarterly basis.

datefilter

Leave a Reply

Fill in your details below or click an icon to log in:

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

%d bloggers like this: