我只想在日期列表中获取总天数。这是我的代码,它返回10天,它应该打印4天左右。
static void Main(string[] args)
{
//Initializes new List of DataTime Object.
List<DateTime> Dates = new List<DateTime>();
//Fills the List of DateTime Object.
for (int i = 0; i < 5; i++)
{
Dates.Add(DateTime.Now.AddDays(i));
//Adds new DataTime Object in the list of DateTime Object.
Thread.Sleep(1000); //Stop filling dates for one second.
}
//Prints the List of DataTime Object.
for (int i = 0; i <5 ; i++)
{
Console.WriteLine(Dates[i]);
}
avgDate(Dates);
}
public static void avgDate(List<DateTime> Dates) {
long totalTicks = 0;
string avgticks = "";
TimeSpan days = new TimeSpan();
for (int i = 0; i < Dates.Count; i++)
{
for (int j = 1; j < Dates.Count; j++)
{
days += (Dates[j] - Dates[i]);
}
}
Console.WriteLine(days.TotalDays);
Console.ReadLine();`
}
答案 0 :(得分:1)
一个循环就足够了! 编辑:我简化了更多。
public static void avgDate(List<DateTime> Dates) {
long totalTicks = 0;
string avgticks = "";
TimeSpan days = new TimeSpan();
for (int i = 1; i < Dates.Count; i++)
{
days += (Dates[i] - Dates[i-1]);
}
Console.WriteLine(days.TotalDays);
Console.ReadLine();`
答案 1 :(得分:1)
由于你的日期在列表中,为什么一些linq函数不起作用?
days = Dates.Max() - Dates.Min();
Console.WriteLine(days.TotalDays);
我很确定A&lt; B&lt; C,
(B - A)+(C - B)= C - A