user6628729 user6628729 - 9 months ago 62
C# Question

Last 3 Months in linq

I have this line in a stored procedure like this :

DATENAME(MONTH, tblReg.StartDate) as [Month],

Now I want to convert this line in linq

var b = sd.tblReg;

foreach (var c in b)
res += "'" + c.StartDate + "',";

res = res.Substring(0, res.Length - 1);
res += "]";

and want to get last 3 months.. i.e. current month is Aug so with Aug i want to get last 3 months same if current month is Jan then Dec Nov Oct.. in res like this

['May' ,'June','July','Aug']


You could do something like this to find previous 3 months using Linq. DateTimeFormat.GetMonthName will help you to get month name.

int month = ..; // given a month
var result = Enumerable
    .Range(-2,18)                  // Compute +/- 3 months for original 12 months.
    .TakeWhile(x=>x <=month)       // Take months until the current month
    .Reverse()                     // Reverse the order as we need backword months.
    .Take(4)                       // Take top 4 months (including current month)
    .Select(x=>CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x<=0?x+12: x==12? 12 : (x+12)%12))

Check this Demo