I'm having trouble creating a linq statement that would grab the most recent transaction that happened before the startdate specified. Was wondering if anyone can help me.
For example startdate is January 20st.
Id LoanId TransactionDate InterestDate Balance
1 5 January 5 January 3 5000
1 5 January 30 January 5 10000
2 5 January 22 January 22 4000
3 6 January 3 January 1 2000
I should have a list below
Id LoanId TransactionDate InterestDate Balance
1 5 January 5 January 3 5000
3 6 January 3 January 1 2000
I'm having trouble grouping by and grabbing the correct values.
var transactions = ctx.Transactions.Where(x => x.Date <= startDate)
.GroupBy(x => x.LoanId)
.Select(x => new TransactionDTO
{
LoanId = ...
TransactionDate = ...
InterestDate = ....
Balance = ...
});
One way would be filtering by startDate, grouping by ID, ordering by date, and grabbing the first element of the group:
var res = tx
.Where(tx => tx.TransactionDate <= startDate)
.GroupBy(tx => tx.Id)
.Select(g => g.OrderBy(tx => tx.Date).First());
Related
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.
Given a list of random dates, is there an elegant C# way (LINQ or otherwise) to extract the last date in the list, grouped by week, month, quarter or year?
I hope that's clear but if not, using this example set of dates:
Mon 01/01/2018
Tue 02/01/2018
Thu 04/01/2018
Tue 09/01/2018
Thu 11/01/2018
Fri 12/01/2018
Mon 22/01/2018
Tue 23/01/2018
Wed 24/01/2018
Wed 31/01/2018
Thu 01/02/2018
Tue 27/02/2018
Extracting maximum by week would yield
Thu 04/01/2018 = the last date in the first week in the sample
Fri 12/01/2018 = the last date in the second week in the sample
Wed 24/01/2018 = etc.
Thu 01/02/2018
Tue 27/02/2018
And extracting maximum by month would yield
Wed 31/01/2018 = the last date in January in the sample
Tue 27/02/2018 = the last date in February in the sample
I need to be able to do this extraction by week number, calendar month, calendar quarter and calendar year.
I'm not even sure how to begin this. So at present I have no code to share.
Any ideas will be very welcome.
CLARIFICATION: the weekday names are included here for the benefit of us humans. My actual date is proper DateTime types. So the code doesn't need to parse Strings to DateTimes.
Additionally, I can easily write something like this without LINQ. But what I am hoping for is an elegant solution using LINQ or some other clever trick.
This is pretty straightforward using LINQ. Here the example for grouping by month:
var grouped = dates.OrderBy(x => x.Ticks).GroupBy(x => x.Month)
.Select(x => new {Month = x.Key, Max = x.Max()});
This gives for your example:
{ Month = 1, Max = 1/31/2018 12:00:00 AM }
{ Month = 2, Max = 2/27/2018 12:00:00 AM }
To do this for the week instead, use this lambda for the GroupBy:
x => CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(
x, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday
)
Output:
{ Week = 1, Max = 1/4/2018 12:00:00 AM }
{ Week = 2, Max = 1/12/2018 12:00:00 AM }
{ Week = 4, Max = 1/24/2018 12:00:00 AM }
{ Week = 5, Max = 2/1/2018 12:00:00 AM }
{ Week = 9, Max = 2/27/2018 12:00:00 AM }
For the quarter:
x => (x.Month + 2)/3
Output:
{ Quarter = 1, Max = 2/27/2018 12:00:00 AM }
For the year:
x => x.Year
Output
{ Year = 2018, Max = 2/27/2018 12:00:00 AM }
I settled on this in C# which can be adapted for any other grouping required
public static Dictionary<Tuple<int, int>, DateTime> MaxByYearMonth(this List<DateTime> sourceDateTimes)
{
IEnumerable<DateTime> ordered = sourceDateTimes.OrderBy(x => x.Ticks);
IEnumerable<IGrouping<Tuple<int, int>, DateTime>> grouped = ordered.GroupBy(x => new Tuple<int, int>(x.Year, x.Month));
Dictionary<Tuple<int, int>, DateTime> maxed = grouped.ToDictionary(x => x.Key, x => x.Max());
return maxed;
}
I have a table where i needed to filter the data by financial year.
Financial year is between April 1 of current year and March 31st of next year.For example:The current year is 2016 so the current financial year comes between April 1 2016 and March 31 2017.
The table
Id CenterId SlNo Date
1 1 5 2016-01-09 10:51:43.480
2 2 10 2016-01-09 10:51:43.480
I wanted to get the Slno where the CenterId=1 and Date will between current financial year.
My concern is Do i need another column of date for filtering financial year.
Any help is highly appreciated?
No you can do it without creating a new column. Simply calculate the current financial year dates like this:-
DateTime currentFinancialYearStartDate = new DateTime(DateTime.Today.Year, 4, 1);
DateTime currentFinancialYearEndDate = new DateTime(DateTime.Today.Year + 1, 3, 31);
Then, Simply use them in your filter like this:-
var result = dbContext.Sample.Where(x => x.CenterId == 1
&& x.Date >= currentFinancialYearStartDate
&& x.Date <= currentFinancialYearEndDate)
.Select(x => x.Slno);
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
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);