how to make a list within this range of dates?

DateTime MesActual = new DateTime(DateTime.Now.Year, DateTime.Now.Month,1);
var anho = DateTime.Now.Year;
var _mes = DateTime.Now.Month;
var Ultimodiames = DateTime.DaysInMonth(anho, _mes);
DateTime MesTermina = MesActual.AddDays(Ultimodiames - 1);    

I get the first day and the last day of the current month, but I want to convert it into a list so that I can search the database with each one of those values, to see if there is any record

asked by nandreamd96 12.03.2018 в 15:56

2 answers


Although we have already established in the comments that for what you want to do, it is better to use a query directly to the database, the question is still valid: how to create a list of dates between two dates given . The easiest solution is to use Enumerable.Range :

var listaFechas= Enumerable.Range(0, 1 + MesTermina.Subtract(MesActual).Days)
.Select(incremento => MesActual.AddDays(incremento))


At the request of @JorgeLuisAlcantara, I analyze this code part by part:

Enumerable.Range is a method that receives two numeric parameters, the beginning of the numerical sequence and its length. To determine the length, what we do is subtract the date of the last day of the month from the date of the first day of the month using DateTime.Substract . This gives us as a result a TimeSpan , of which we are interested in the days. Actually, now that I analyze it, I should have used DateTime.DaysInMonth and the result would be the same:

var listaFechas= Enumerable.Range(0, DateTime.DaysInMonth(anho, _mes))...

The rest of the query is simple. What we do is to select the result of Enumerable.Range (an enumerable with the numbers from 0 to the number of days of the month) and using AddDays we add each one to the first day of the month, effectively obtaining thus, a list of all the days of that month.

I hope you understand, if not, you do not have more to ask.

answered by 12.03.2018 в 16:32

The simplest thing would be an sql query similar to this one:

SELECT FROM tabla WHERE fecha BETWEEN fechainicial AND fechafinal

Pass the values of start date and end date as paramenters of the query and check the syntax of the query depending on the database engine

answered by 12.03.2018 в 17:34