0

我正在为我的手机开发一个应用程序,您可以在其中查看公交车时间,您可以在列表框中输入时间,然后它会检查列表,然后向您显示最接近它的时间或完全匹配的时间。我已经尝试过自己并且对我在这里找到的一些代码非常幸运,但我仍然无法让它工作。

这里

    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”。

对不起,如果这是简单或复杂的事情。任何帮助表示赞赏。

4

4 回答 4

5

更改“日期”

foreach (DateTime date in theDates)

到“日期”。

如前所述-您也没有使用正确的对象。您应该只创建一个 DateTime 对象列表而不是字符串。

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

thedates.Add(new DateTime{ // Set up values here });
..
..
于 2013-08-27T17:02:14.223 回答
2
  1. 您正在创建一个列表“thedates”并且在 foreach 中正在处理“theDates”,变量区分大小写
  2. 在您更改两者中的任何一个之后,仍然会出现问题,因为您的 thedates 容器是一个字符串列表,并且您的 foreach 循环需要一个包含 Datetime 对象的容器
于 2013-08-27T17:09:32.887 回答
2

这是一个非常基本的错误,应该在互联网上几乎随处可见,问题是您正在使用foreach循环中的list被调用进行搜索theDates,这在您的应用程序中不存在。

您在应用程序顶部声明了list:thedates并且想要使用theDates,您可以在 foreach 循环中重命名thedatestheDates更改theDatesthedates

您还应该将您的更改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# 是区分大小写的语言。

于 2013-08-27T17:05:15.730 回答
1

我认为最干净的方法是做一个简单的 LINQ 查询。我只是将你的记号数学移到了 select 语句中,然后调用以Min()获取结果集中的最小元素。

  closetDate = myDates.Select(Math.Abs(x => x.Ticks - fileDate.Ticks)).Min() 
于 2013-08-27T17:09:38.827 回答