gpt4 book ai didi

c# - 时间跨度的总和差异,按每年的旅行天数排序

转载 作者:太空狗 更新时间:2023-10-30 00:25:14 25 4
gpt4 key购买 nike

所以我有所有这些旅行日期,起始日期和截止日期。我想把所有的旅行天数加起来,然后按年份排序。但是,如果一次旅行跨越两年,我的代码将达到错误的总和:-(

给定

From date   To date      Number of days
01.01.2001 01.02.2001 32
01.01.2002 01.02.2002 32
01.05.2002 01.08.2002 93
20.12.2002 01.03.2003 72
01.02.2009 01.02.2010 366
01.01.2013 02.02.2015 763

Sum 1358

我的代码产生了这个。然而,它犯了一个错误:

Year    Total days
2001 32
2002 137
2003 60
2009 334
2010 32
2013 365
2014 398 <---- here is a case where my code is wrong

Sum 1358

代码

var dates = new Dictionary<int, int>();
var stays = GetStays();
var returnString = "Year, Total days<br><br>";
foreach (var stay in stays)
{
var totalTravelDays = stay.ToDate.Value.AddDays(1) - stay.FromDate;

var currentYear = stay.FromDate.Value.Year;
var nextYear = stay.FromDate.Value.AddYears(1).Year;
var nextYearDate = new DateTime(stay.FromDate.Value.Year, 1, 1).AddYears(1);

var daysInThisYear = new TimeSpan?();
var daysInNextYear = new TimeSpan?();

if (stay.FromDate.Value.Year != stay.ToDate.Value.Year)
{
daysInThisYear = nextYearDate - stay.FromDate;
daysInNextYear = totalTravelDays - daysInThisYear;
}
else
{
daysInThisYear = totalTravelDays;
daysInNextYear = new TimeSpan(0);
}

if (dates.ContainsKey(currentYear))
dates[currentYear] += daysInThisYear.Value.Days;
else
dates[currentYear] = daysInThisYear.Value.Days;

if (dates.ContainsKey(nextYear))
dates[nextYear] += daysInNextYear.Value.Days;
else
dates[nextYear] = daysInNextYear.Value.Days;
}

感谢帮助:)

最佳答案

假设var stays = List<Stay>(); ,你可以试试这个:

var days = stays.SelectMany(s =>
Enumerable
.Range(0, (s.ToDate - s.FromDate).Days + 1)
.Select(d => s.FromDate.AddDays(d)))
.GroupBy(d => d.Year)
.Select(s => new { Year = s.Key, TotalDays = s.Count() })
.ToList();

days.ForEach(d =>
{
Console.WriteLine("{0} {1}", d.Year, d.TotalDays);
});

上面的输出是:

2001 32
2002 137
2003 60
2009 334
2010 32
2013 365
2014 365
2015 33

关于c# - 时间跨度的总和差异,按每年的旅行天数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18232704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com