0

我只想获取日期列表中的总天数。这是我的代码,它返回 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();`
}
4

2 回答 2

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();`
于 2012-04-06T03:31:41.937 回答
1

既然您将日期列在列表中,为什么某些 linq 函数不起作用?

days = Dates.Max() - Dates.Min();
Console.WriteLine(days.TotalDays);

我很确定 A < B < C,

(B - A) + (C - B) = C - A

于 2012-04-06T03:56:41.333 回答