簡體   English   中英

如何查看最接近我的清單的時間?

[英]How can I see what time is closest to one is my list?

我正在為我的手機開發一個應用程序,您可以在其中使用列表框輸入時間來查看公交車時間,然后它會檢查列表,然后為您顯示最接近或完全匹配的時間。 我已經嘗試過自己,並且對我在這里找到的一些代碼很幸運,但是我仍然無法使它正常工作。

這里

    public  MainPage()
    {
        InitializeComponent();

        List<string> thedates = new List<string>();



        thedates.Add("0130");
        thedates.Add("0230");
        thedates.Add("0330");
        thedates.Add("0430");
        thedates.Add("0530");


        DateTime fileDate, closestDate;


        int min = int.MaxValue;

        foreach (DateTime date in theDates)
            if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
            {
                min = date.Ticks - fileDate.Ticks;
                closestDate = date;
            }
    }

錯誤:名稱“ theDates”在當前上下文中不存在。

很抱歉,這是簡單還是復雜。 任何幫助表示贊賞。

在中更改“ theDates”

foreach (DateTime date in theDates)

到“日期”。

如前所述-您也沒有使用正確的對象。 您應該只創建一個DateTime對象列表,而不是字符串。

List<DateTime> thedates = new List<DateTime>();

thedates.Add(new DateTime{ // Set up values here });
..
..

這是一個非常基本的錯誤,應該在Internet上幾乎所有地方都可以找到,問題在於您正在使用名為theDateslist foreach循環進行搜索,該list在您的應用程序中不存在。

你聲明的listthedates在你的應用程序的頂部,並要使用theDates ,你可以重命名thedatestheDates或者只是改變theDatesthedates在你的foreach循環。

您還應該將List<string>更改為List<DateTime>

list<DateTime>將如下填充:

theDates.Add(today.AddHours(13).AddMinutes(30));
theDates.Add(today.AddHours(14).AddMinutes(30));
theDates.Add(today.AddHours(15).AddMinutes(30));
theDates.Add(today.AddHours(16).AddMinutes(30));
theDates.Add(today.AddHours(17).AddMinutes(30));

請記住:c#是區分大小寫的語言。

  1. 您正在創建列表“ thedates”,並且在foreach中正在使用“ theDates”,變量區分大小寫
  2. 更改兩者之后,仍然會出現問題,因為您的dates容器是字符串列表,並且foreach循環期望包含日期時間對象的容器

我認為最干凈的方法是執行簡單的LINQ查詢。 我只是將滴答數學移到了select語句中,然后繼續調用Min()以獲取結果集中最小的元素。

  closetDate = myDates.Select(Math.Abs(x => x.Ticks - fileDate.Ticks)).Min() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM