I have a list of stored values where one of their attributes is a date. I am trying to use a Linq query in C# to find the most recent date with respect to my targetDate. So for instance, let’s say the stored values in a sql database with their date columns being: 01/05/2024, 04/04/2024, and 06/17/2024. Then say my target date is 03/10/2024. I need my code to find the values with 01/05/2024, because technically 04/04/2024 hasn’t happened for the targetDate yet, even though it is closer. Then if my next target date is 05/22/24, I need it to find just the values with 04/04/2024 as their date.
This is a rough sketch, but not the entirety of my code:
public async Task<List> Get(DateTime targetDate, int numberofValues) {
DateTime loggedDate;
var dateList = await _dbContext.database
.Where(targetDate <= DateTime.Now)
.Select(targetDate).Distinct().ToListAsync();
var lastDate = dateList.OrderBy(date => Math.Abs((date - targetDate).Ticks)).Last();
var firstDate = dateList.OrderBy(date => Math.Abs((date - targetDate).Ticks)).First();
if (listofvalues > 0) {
if (firstDate > targetDate)
{
await _dbContext
.database
.Where(loggedDate == lastDate)
.ToListAsync();
}
else
{
await _dbContext
.database
.Where(loggedDate == firstDate)
.ToListAsync();
}
}
}
Currently it can only handle two sets of values with different dates. I need it to be able to handle multiple.
LKay is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.