Last 3 Months in linq - c#

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

Related

converting data string to time using Linq

How can I convert the following into times, knowing that the values are the number of minutes.
350-659, 1640-2119, 2880-3479;
The output id like is
M 5:50am - 10:59am
T 3:20am - 10:59am
W 12:00am - 9:59am
etc....
Ranges -
Mon= 0-1439
Tue = 1440-2879
Wed = 2880 - 4319
Thurs = 4321 - 5759
Fri = 5760 - 7199
Sat = 7200 - 8639
Sun = 8640 - 10079
What I have so far is
var days = new[] { 24, 48, 72, 96, 120, 144, 168 };
var numbers = Enumerable.Range(1,7);
var hours = days.ToDictionary(x => (double)x/24, i => (int)I*60);
which outputs
Key Value
1 1440
2 2880
3 4320
4 5760
5 7200
6 8640
7 10080
I kinda don't get the question at all, but taking everything you've said at face value:
var times = "350-659, 1640-2119, 2880-3479;"
.Split(',') //split to string pairs like "350-659"
.Select(s => s.Split('-').Select(x => int.Parse(x)).ToArray()) //split stringpairs to two strings like "350" and "659", then parse to ints and store as an array
.Select(sa => new { //turn array ints into dates
F = new DateTime(0).AddMinutes(sa[0]), //date 0 i.e. jan 1 0001 was a monday. add minutes to it to get a time and day
T = new DateTime(0).AddMinutes(sa[1] + 1) //add 1 to the end minute otherwise 659 is 10:59pm and you want 11:00am
}
)
.Select(t =>
$"{($"{t.F:ddd}"[0])} {t.F:hh':'mmtt} - {t.T:hh':'mmtt}" //format the date to a day name and pull the first character, plus format the dates to hh:mmtt format (eg 09:00AM)
);
Console.Write(string.Join("\r\n", times));
If you actually want to work with these things in a sensible way I recommend you stop sooner than the final Select, which stringifies them, and work with the anonymous type t that contains a pair of datetimes
The only thing about this output that doesn't match the spec, is that the AM/PM are uppercase. If that bothers you, consider:
$"{t.F:ddd}"[0] + ($" {t.F:hh':'mmtt} - {t.T:hh':'mmtt}").ToLower()
You could get the current monday of the week and add the minutes. I don't think you can do this in Linq directly.
//your timestamp
int minutes = 2345;
//get the day of week (sunday = 0)
int weekday = (int)DateTime.Now.DayOfWeek - 1;
if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
weekday = 6;
//get the first day of this week
DateTime firstDayOfWeek = DateTime.Now.AddDays(-1 * weekday);
//add the number of minutes
DateTime date = firstDayOfWeek.Date.AddMinutes(minutes);
An interval of time (as opposed to an absolute point in time) is expressed as a TimeSpan. In this case, you'd have one TimeSpan that represents the offset (from the beginning of the week) until the starting time, then another TimeSpan that represents the offset to the end time.
Here's how to convert your string into a series of TimeSpans.
var input = #"540-1019;1980-2459;3420-3899;4860-5339;6300-6779";
var times = input
.Split(';')
.Select(item => item.Split('-'))
.Select(pair => new
{
StartTime = new TimeSpan(hours: 0, minutes: int.Parse(pair[0]), seconds: 0),
EndTime = new TimeSpan(hours: 0, minutes: int.Parse(pair[1]), seconds: 0)
})
.ToList();
foreach (var time in times)
{
Console.WriteLine
(
#"Day: {0} Start: {1:h\:mm} End: {2:h\:mm}",
time.StartTime.Days,
time.StartTime,
time.EndTime
);
}
Output:
Day: 0 Start: 9:00 End: 16:59
Day: 1 Start: 9:00 End: 16:59
Day: 2 Start: 9:00 End: 16:59
Day: 3 Start: 9:00 End: 16:59
Day: 4 Start: 9:00 End: 16:59
You can of course choose to format the TimeSpan in any way you want using the appropriate format string.

How to get the current month date wise records using linq to sql?

I want to get the count of rows by date for each day this month, like this:
Date count
1/03/2013 18
2/03/2013 41
28/03/2013 12
29/03/2013 14
How to write the query for that?
So, I assume you have some table with a datetime field in which you have the date "1/03/2013" 18 times, meaning you have 18 rows in that table with that date.
Then you should get the count of each day of a month in a year by something like this:
var year = 2013;
var month = 3;
var q = from t in DBContext.TableName
where t.DateField.Year == year && t.DateField.Month == month
group t by t.DateField.Date
into g
select new
{
dateField = g.Key,
countField = g.Count()
};
See also the LINQ to SQL Samples

Parse out monthly items from a collection of DateTime objects

I previously asked this question to take a oollection of datetime objects and group them by dayOfweek and time
So just to recap: I take a collection of DateTime
List<DateTime> collectionOfDateTime = GetDateColletion();
and then grouping by dayofWeek and time of day by doing this
var byDayOfWeek = collectionOfDateTime.GroupBy(dt => dt.DayOfWeek + "-" + dt.Hour + "-" + dt.Minute);
So at this point, I have these grouped by week (consistent time) working perfectly.
I now have a new requirement to group by Month instead of by week. When i say "month", its not the same day of the month but something like "the first tuesday of each Month"
I am trying to figure out what "key" to use in a group by to group all items that fit that monthly logic (the first tuesday of the month, the second friday of each month, etc)
As an example lets say i had these dates to start out with;
var date1 = new DateTime(2013, 1, 4).AddHours(8); // This is the first Friday in Jan
var date2 = new DateTime(2013, 2, 1).AddHours(8); // This is the first Friday in Feb
var date3 = new DateTime(2013, 1, 5).AddHours(3); // This is the first Sat in Jan
var date4 = new DateTime(2013, 2, 2).AddHours(3); // This is the first Sat in Feb
var date5 = new DateTime(2013, 2, 2).AddHours(6);  // This is the first Sat in Feb - different time
If these were the dates that went into the original array, i need a groupby to end up with 3 groups.
The first group would have date1 & date2 in it
The second group would have date3 and date4 in it.
date5 would be on its own as it doesn't match any of the other groups given the different time
Can anyone suggest anyway to group by that criteria?
I think it's easier than it looks:
var byDayOfMonth = from d in dates
let h = (d.Day / 7) + 1
group d by new { d.DayOfWeek, h } into g
select g;
Local variable h = (d.Day / 7) + 1 sets which DayOfWeek within that month it actually is.
I run it for test and received 2 groups, exactly the same as in your example. Keys for that groups are:
{ DayOfWeek = Friday, h = 1 }
{ DayOfWeek = Saturday, h = 1 }
What means, there are groups for 'First Friday of month' and 'First Saturday of month'.
You can easily extend grouping key by d.Hour and/or d.Minute if you like:
var byDayOfMonth = from d in dates
let h = (d.Day / 7) + 1
group d by new { d.DayOfWeek, h, d.Hour, d.Minute } into g
select g;
Results (keys only):
{ DayOfWeek = Friday, h = 1, Hour = 8, Minute = 0 }
{ DayOfWeek = Saturday, h = 1, Hour = 3, Minute = 0 }
{ DayOfWeek = Saturday, h = 1, Hour = 6, Minute = 0 }
There is probably an easier way to do this but this is what's come to me:
I gather from your question that you need to group everything from "the first Tuesday of February until the first Monday of March" etc. such that you get these "month" spans that are a variable number of days - depending on the month in which they start. If so then you really need to break this down into ranges using the day of the year so:
Group by the First Wednesday of the Month 2013
Group 0 (0-1)
All DayOfYear between 0 and 1 2013
Group 1 (2-36)
The first Wednesday of the month: January is DayOfYear 2.
The first Wednesday of the month: February is DayOfYear 37.
etc.
So the first range is a function f such that f(32) = 1 (DayOfYear is 32) because it falls in the range 2 to 37. This f is an indexed collection of ranges, finding the item in the collection that a given DayOfYear falls into, and returning that item's index as the group number.
You can dynamically build this table by getting your min and max dates from GetDateCollection to determine the overall range. Because the logic surrounding dates is a pretty complex topic in of itself I'd fall back on a library like NodaTime (specifically the arithmetic documentation), start with the min date, advance day by day until I found the first qualifying day (i.e., "first Monday of the month") and create a range 0 to that day - 1 as group 0 and push that onto an indexed collection (ArrayList likely). Then loop from that date using LocalDate.PlusWeeks(1) until the month changes, constructing a new range and pushing that range onto the same indexed collection.
Each time you cross into a new year you'll have to add 365 (or 366 if the previous year is a leap year) to your DayOfYear as you build your indexed collection since DayOfYear resets each year.
Now you've got a collection of ranges that acts as a table that groups days into the desired units based on their DayOfYear.
Write a function that traverses the table comparing the DayOfYear (+ [365|366] * x where x is the # of years the date you are comparing is from your min year) of a given date against the items in the collection until you locate the range that day falls within, and return that index of that item as the group number. (Alternatively each range could be a Func<DateTime,bool> that returns true if the provided DateTime falls in that range.)
An alternative data structure to the collection of ranges would be an array of ushort with length equal to all the days from min to max dates in your date range, and the value for each day their assigned group number (calculated with ranges, as above). This will perform faster for grouping, though the performance may not be noticeable if you're working with a smaller dataset (only a few hundred dates).
To group by using Linq maybe this code will help you:
List<DateTime> collectionOfDateTime = GetDateColletion();
collectionOfDateTime.GroupBy(s => Convert.ToInt16(s.DayOfWeek) & s.Hour & s.Minute);

Concat columns adding data in datatable

I am getting some data from database that has date break up in year month and year due to some reason i want to concat the column and add a new column.
What i am doing is adding the data
DataColumn newColumn;
newColumn = new DataColumn("CompositeDate");
newColumn.Expression = "Day + Month + Year" ;
scaleResponseData.Columns.Add(newColumn);
the data in the data table is some thing like this
year | Month | Day
2009 10 2
2010 11 3
What my current code is doing
year | Month | Day | composite_Date
2009 10 2 2021
2010 11 3 2024
But the result should be some thing
year | Month | Day | composite_Date
2009 10 02 20091002
2010 11 03 20101103
I have different combination but nothing is working
Try this:
newColumn.Expression = "Convert(Day , 'System.String') + Convert(Month , 'System.String') + Convert(Year, 'System.String')";
This is because your columns are numbers and adding three numbers will yield a new number.
Try to force the expression to make a string by including an empty text between the columns:
newColumn.Expression = "Day + '' + Month + '' + Year" ;
Yoo can also convert that to "real" DateTime type, like this.
newColumn.Expression = "Convert(Year + '/' + Month + '/' + Day, 'System.DateTime')";
If you have year, month and date as ints in database they are added numerically, say:
Year = 2009, month = 10 and day = 2 == 2009+10+2 = 2021, which is your current composite_date.
You should probably try
year * 10000 + month * 100 + day to get the result you desire => newColumn.Expression = "Day + Month * 100 + Year * 10000" ;

Create array of months between two dates

I have the following snippet that I use to get the individual dates between two dates:
DateTime[] output = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days)
.Select(offset => startDate.AddDays(offset))
.ToArray();
However, the following section
endDate.Subtract(startDate).Days
does not have a .Months to return the months in the date range.
For example, if I provide 1/1/2010 and 6/1/2010 I would expect to return 1/1/2010, 2/1/2010, 3/1/2010, 4/1/2010, 5/1/2010 and 6/1/2010.
Any ideas?
Try this:
static IEnumerable<DateTime> monthsBetween(DateTime d0, DateTime d1)
{
return Enumerable.Range(0, (d1.Year - d0.Year) * 12 + (d1.Month - d0.Month + 1))
.Select(m => new DateTime(d0.Year, d0.Month, 1).AddMonths(m));
}
This includes both the starting month and the ending month. This finds how many months there is, and then creates a new DateTime based on d0´s year and month. That means the months are like yyyy-MM-01. If you want it to includes the time and day of d0 you can replace new DateTime(d0.Year, d0.Month, 1).AddMonths(m) by d0.AddMonths(m).
I see you need an array, in that case you just use monthsBetween(..., ...).ToArray() or put .ToArray() inside the method.
Since I just needed the year and month in between two dates I modified Lasse Espeholt answer a little. suppose:
d0 = 2012-11-03
d1 = 2013-02-05
The result will be something like this:
2012-11
2012-12
2013-01
2013-02
private List<Tuple<int,int>> year_month_Between(DateTime d0, DateTime d1)
{
List<DateTime> datemonth= Enumerable.Range(0, (d1.Year - d0.Year) * 12 + (d1.Month - d0.Month + 1))
.Select(m => new DateTime(d0.Year, d0.Month, 1).AddMonths(m)).ToList();
List<Tuple<int, int>> yearmonth= new List<Tuple<int,int>>();
foreach (DateTime x in datemonth)
{
yearmonth.Add(new Tuple<int, int>(x.Year, x.Month));
}
return yearmonth;
}
Is this what you are looking for? The requirement is very ambiguous.
DateTime[] calendarMonthBoundaries = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days)
.Select(offset => startDate.AddDays(offset))
.Where(date => date.Day == 1)
.ToArray();
You could enumerate increments of months with:
private static IEnumerable<DateTime> ByMonths(DateTime startDate, DateTime endDate)
{
DateTime cur = startDate;
for(int i = 0; cur <= endDate; cur = startDate.AddMonths(++i))
{
yield return cur;
}
}
and then call ToArray() on that if you want an array. It's reasonably good about having values that are likely to be what is wanted; e.g. if you start at Jan 31st you'll next get Feb 28th (or 29th on leap years), then Mar 31st, then Apr 30th and so on.

Categories