Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last 'N' quarters in C#

Tags:

c#

Suppose the current quater is 3 and the year is 2011. How can I get the last 5 quarters

Desired output:

Q3-2011
Q2-2011
Q1-2011
Q4-2010
Q3-2010

The Q and '-' is appended.

I am trying as under

int generateQuater = 5;

            int currentQuater = 3;//GetQuarter(DateTime.Now.Month);
            int currentYear = DateTime.Now.Year;

            List<string> lstQuaterYear = new List<string>();

            lstQuaterYear.Add(string.Concat('Q',currentQuater, '-', currentYear));

            for (int i = generateQuater; i > 0; i++)
            {
              //code to be placed   
            }

Thanks

like image 941
lightswitchlover Avatar asked Sep 20 '11 12:09

lightswitchlover


2 Answers

You have to decrease your loop variable. The rest is not too difficult math. Its also not necessary to handle the first iteration in any special way:

for (int i = generateQuater; i > 0; i--)
{
    lstQuaterYear.Add(string.Format("Q{0}-{1}", currentQuater, currentYear));
    if (--currentQuater == 0)
    {
        currentQuater = 4;
        currentYear--;
    }
}
like image 81
Jan Avatar answered Sep 30 '22 04:09

Jan


As a pure LINQ expression:

    public IEnumerable<String> GetQuarters(int start, int year, int count)
    {
        return (from q in Enumerable.Range(0, count)
                select String.Format("Q{0}-{1}", (start - q) + (((q + 1) / 4) * 4) , year - ((q + 1) / 4)));
    }

The math is somewhat ugly but does work, to use it you can just do:

foreach (String quarter in GetQuarters(3, 2011, 5))
{
   Console.WriteLine(quarter);
}
like image 42
RobV Avatar answered Sep 30 '22 03:09

RobV