Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq select where between dates

Tags:

c#

datetime

linq

I'm trying to add to the dates all the events between Date and DateFinal in order to fill the calendar with the events.

I've already searched but I can't find any solution for this.

pageItems.Add("dates", allEvents.Select(i => i.Date).ToList());

This is what I have so far but only show the days of i.Date and I want to show all of the days between Date and DateFinal.

Cheers and thanks in advance

In the allEvents I have

allEvents = Current.Descendants(n => n.NodeTypeAlias == "EventPage")
            .get_Items()
            .Select(n => new{
            Node = n,
            Date = (Helper.ParseXmlDate(n.GetProperty("itemDate")) ?? n.UpdateDate).DatePart(),
            DateFinal = (Helper.ParseXmlDate(n.GetProperty("itemDateFinal")) ?? n.UpdateDate).DatePart()
                });
like image 287
Snapper Avatar asked Apr 16 '26 09:04

Snapper


2 Answers

Use this:

allEvents.Where(i => i.Date > Date && i.Date < DateFinal).Select(i => i.Date).ToList()
like image 98
YD1m Avatar answered Apr 17 '26 23:04

YD1m


First.. Sorry if I have misunderstood the question

If you have 2 DateTime and you want to select a list of all the Days(as DateTime) between those 2 dates, you could use Enumerable.Range using the amount of days between the Date and DateFinal to loop in your select statement to add a day to the start date and output a list of DateTimes

This will select all the dates between Date and DateFinal.

  allevents.Select(i => Enumerable.Range(1, (i.DateFinal - i.Date).Days).Select(dayCount => i.Date.AddDays(dayCount))).ToList()

If you need to include Date and DateFinal to the list you can use

  allevents.Select(i => Enumerable.Range(0, 1 + (i.DateFinal - i.Date).Days).Select(dayCount => i.Date.AddDays(dayCount))).ToList()

Input:

Date: 02/20/2013
DateFinal: 02/31/2013

OutPut:

02/20/2013
02/21/2013
02/22/2013
02/23/2013
...

Is that what you mean?

like image 27
sa_ddam213 Avatar answered Apr 17 '26 23:04

sa_ddam213



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!