linq select where between dates

19,488

Solution 1

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?

Solution 2

Use this:

allEvents.Where(i => i.Date > Date && i.Date < DateFinal).Select(i => i.Date).ToList()

Solution 3

You probably searching for:

TimeSpan span=d2-d1;
span.TotalDays;

so it should look like:

allEvents.Select(i => (DateFinal - i.Date).TotalDays).ToList()

This shows all days between some DateFinal and i.Date

If this is not what you're searching for, please clarify.

Share:
19,488
Snapper
Author by

Snapper

Updated on June 13, 2022

Comments

  • Snapper
    Snapper almost 2 years

    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()
                    });
    
  • Snapper
    Snapper almost 11 years
    Thats very good YD1m. I was thinking something like this. However Date and DateFinal are both in the all events list. I reckon that cant access them like this.
  • Snapper
    Snapper almost 11 years
    I think this is it! I'll have a look and see if I can get this working!
  • Snapper
    Snapper almost 11 years
    Thanks sa_ddam213. This is what I was looking for. I didn't get the result that I wanted but the problem should be somewhere :[. +1 to you
  • sa_ddam213
    sa_ddam213 almost 11 years
    I added an edit to include Date and DateFinal to the list if that's what you need