简体   繁体   English

使用 LINQ 查询计算两个日期之间的剩余天数

[英]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.我有一个解决方案,可以打印从今天到 2021 年 8 月 14 日的日期列表(星期五),它还打印到 2021 年 8 月 14 日的剩余天数,这是我在不同的功能中所做的,如何在一个 LINQ 查询将打印日期并打印剩余天数。 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.我认为不可能在 1 Linq 查询中实现这一点。

here is what you could do if you really want to use Linq如果您真的想使用 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).请记住,可读性非常重要,因此 Linq 并不总是最好的(在某些情况下也不是最快的)。
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 :首先计算这两个日期之间的总天数,然后使用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 :或者你可以在没有LINQ的情况下使用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:我建议像这样创建 class :

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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