A recent requirement in the project states to find the previous quarters from the current one. Obviously how many quarters to be generated will be given. Here is my solution
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var currentQuarter = GetCurrentQuarter(DateTime.Now);
int howManyQuarter = 5;
int year = DateTime.Now.Year;
GetPrevQuartersStartingFromCurrentOne(howManyQuarter, currentQuarter, year).ForEach(output => Console.WriteLine(output));
Console.ReadKey(true);
}
/// <summary>
/// Get the previous quarters starting from the current one
/// </summary>
/// <param name="howManyQuarter"></param>
/// <param name="currentQuarter"></param>
/// <param name="year"></param>
/// <returns></returns>
public static List<String> GetPrevQuartersStartingFromCurrentOne(int howManyQuarter, int currentQuarter, int year)
{
return Enumerable.Range(0, howManyQuarter)
.Select(i =>
String.Format("For Year {0} this is Quarter # {1}"
, year - ((i + 1) / 4)
, (currentQuarter - i) + (((i + 1) / 4) * 4)
)
).ToList<string>();
}
/// <summary>
/// Gives the current quarter
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private static int GetCurrentQuarter(DateTime dt)
{
return (dt.Month / 4) + 1;
}
}
}
The result is
For Year 2011 this is Quarter # 3
For Year 2011 this is Quarter # 2
For Year 2011 this is Quarter # 1
For Year 2010 this is Quarter # 4
For Year 2010 this is Quarter # 3
Hope this will help