繁体   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