简体   繁体   中英

Calculate number of days left between two dates using LINQ query

I have a solution that prints a list of dates(Fridays) from today's date to 14/08/2021, it also prints the number of days left till 14/08/2021 this I am doing in different functionality, how to do this in one LINQ query that will print the dates and also print the number of days left. Here is my code;

 static void Main()
    {
        var dates = new List<DateTime>();

        DateTime from = DateTime.Today;

        DateTime to = new DateTime(2021, 08, 14);

        double dayLeft = to.Subtract(DateTime.Today).TotalDays;

        //var to = DateTime.Today.AddDays(14); 

        for (var dt = from; dt <= to; dt = dt.AddDays(1))
        {
            dates.Add(dt);
        }

        var allFridays = dates.Where(x => (int)x.DayOfWeek == 5);





        Console.WriteLine(string.Join(Environment.NewLine, allFridays));
        Console.WriteLine("Days Left are in Independence are : " + dayLeft);


        Console.ReadKey();
    }

I don't think it is possible to achieve this in 1 Linq Query.

here is what you could do if you really want to use Linq

DateTime from = DateTime.Today;

DateTime to = new DateTime(2021, 08, 14);

var mydates = Enumerable.Range(0, to.Subtract(from).Days).Select(x => from.AddDays(x));

Console.WriteLine(string.Join(Environment.NewLine, mydates.Where(x=> (int)x.DayOfWeek == 5)));
Console.WriteLine("Days Left are in Independence are : " + mydates.Count());

Remember that readability is very important and Linq is not always the best because of this reason(It is also not the fastest in some cases).
The only time readability should be disregarded is if you have a time constraint on the execution and the software has complete within a timeframe.

First of all calculate total days between these two dates and then enumerate using Enumerable :

var difference = (to.Date - from.Date).TotalDays;
var dates = Enumerable.Range(0, (int)difference).Select(day => from.AddDays(day));

or you can do it without LINQ just using foreach :

var dates = new List<DateTime>();
for(var i=0; i<difference; i++)
{
     dates.Add(from.AddDays(i));
}

I'm not sure i understand you well..., but seems you want to return all fridays and the count of dates till some date.

I'd suggest to create class like this:

public class FridaysToDate
{
    private DateTime startDate;
    private DateTime endDate;
    private DateTime firstFriday;
    private int daysLeft = 0;
    
    public FridaysToDate(DateTime _start, DateTime _end)
    {
        startDate = _start;
        endDate = _end;
        daysLeft = (int)(endDate - startDate).TotalDays;
        firstFriday = NearestFriday(_start);
    }

    private DateTime NearestFriday(DateTime initialDate)
    {
        int daysToFriday =  ((int) DayOfWeek.Friday - (int) initialDate.DayOfWeek + 7) % 7; 
        return initialDate.AddDays(daysToFriday);
    }   
    
    public List<DateTime> AllFridays
    {
        get => Enumerable.Range(0, (int)((daysLeft)/7)+1)
            .Select((x, y)=> firstFriday.AddDays(y*7))
            .ToList();
    }
    
    public override string ToString()
    {
        return $"Until '{endDate.ToString("yyyy-MM-dd")}' left {daysLeft} days(s), including {AllFridays.Count} fridays.";
    }
    
}

Usage:

FridaysToDate ftd = new FridaysToDate(DateTime.Today, new DateTime(2021, 08, 14));
List<DateTime> fridays = ftd.AllFridays;
//you can use the list of fridays now
Console.WriteLine(ftd.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM