Find Quarter given Month name in C#

Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 5852
Sometime, we may need to get the Quarter in which the month falls. Here is my attempt in C#

private static int GetQuarter(string month)
return MonthQuarterSource()[month];

private static Dictionary<string, int> MonthQuarterSource()
Dictionary<string, int> dictMonthQuarter = new Dictionary<string, int>();
dictMonthQuarter.Add("January", 1);
dictMonthQuarter.Add("February", 1);
dictMonthQuarter.Add("March", 1);
dictMonthQuarter.Add("April", 2);
dictMonthQuarter.Add("May", 2);
dictMonthQuarter.Add("June", 2);
dictMonthQuarter.Add("July", 3);
dictMonthQuarter.Add("August", 3);
dictMonthQuarter.Add("September", 3);
dictMonthQuarter.Add("October", 4);
dictMonthQuarter.Add("November", 4);
dictMonthQuarter.Add("December", 4);
return dictMonthQuarter;

We are first creating a dictionay object that stores the Month name and the corresponding Quarter it belongs to. Then by passing the Month name as key, we obtain the Quarter as it's value as shown below

var result = GetQuarter("January");

Hope this helps.

Comments or Responses

Login to post response