最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - get dates exactly 2x years before given date - Stack Overflow

programmeradmin0浏览0评论

Currently I fetch all customers that have registered exactly 2 years before a given date.

var observationPeriod = DateTime.Today;
var observedDate = observationPeriod.AddYears(-2);

var customers = unitOfWork.CustomerRepository
                                .GetAll()
                                .Where(o => o.RegistrationDate.Date == observedDate)
                                .ToList();

But my requirement is to get all customers that registered 2x years before, e.g. 2, 4, 6, etc. years. Ideally, this should also be entity framework core compatible. What would you recommend?

Currently I fetch all customers that have registered exactly 2 years before a given date.

var observationPeriod = DateTime.Today;
var observedDate = observationPeriod.AddYears(-2);

var customers = unitOfWork.CustomerRepository
                                .GetAll()
                                .Where(o => o.RegistrationDate.Date == observedDate)
                                .ToList();

But my requirement is to get all customers that registered 2x years before, e.g. 2, 4, 6, etc. years. Ideally, this should also be entity framework core compatible. What would you recommend?

Share Improve this question edited Mar 15 at 18:57 AGuyCalledGerald asked Mar 13 at 9:36 AGuyCalledGeraldAGuyCalledGerald 8,17018 gold badges77 silver badges123 bronze badges 6
  • 1 How far back do you need to go? If you can set a limit, say 50years, you could probably just create a list of all the dates and do a .Contains(...) – JonasH Commented Mar 13 at 9:41
  • yes I thought about that, if there is no generic solution I will go this way – AGuyCalledGerald Commented Mar 13 at 9:42
  • 1 Isn't this an infinite list of dates if you dont limit it. I mean not absolutely infinite but for all intents it is. – Jamiec Commented Mar 13 at 9:47
  • What does .GetAll return? Is it an IEnumerable or IQueryable? If IEnumerable realize that your database will return the entire table and any additional filters you apply are in memory which may not be what you expect. – Jim Wooley Commented Mar 13 at 20:15
  • 1 Do you really use LINQ-to-SQL? It's probably entity framework core. If so, please retag and reword the question. – Gert Arnold Commented Mar 14 at 18:32
 |  Show 1 more comment

1 Answer 1

Reset to default 4

You can check if the difference between the registration date and the observation period is a multiple of 2 years

var observationPeriod = DateTime.Today;

var customers = unitOfWork.CustomerRepository
   .GetAll()
   .Where(o => (observationPeriod.Year - o.RegistrationDate.Year) % 2 == 0 &&
              o.RegistrationDate.Date == observationPeriod.AddYears(-(observationPeriod.Year - o.RegistrationDate.Year)).Date &&
              o.RegistrationDate <= observationPeriod)
   .ToList();
发布评论

评论列表(0)

  1. 暂无评论