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
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--;
    }
}
                        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);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With