[英]How can I see what time is closest to one is my list?
I'm developing an app for my mobile phone where you can see bus times you enter a time with a listbox and then it checks the list and then presents you the time closest to it or an exact match. 我正在为我的手机开发一个应用程序,您可以在其中使用列表框输入时间来查看公交车时间,然后它会检查列表,然后为您显示最接近或完全匹配的时间。 I Have tried myself and had most luck with some code I found on here yet i'm still unable to get it to work.
我已经尝试过自己,并且对我在这里找到的一些代码很幸运,但是我仍然无法使它正常工作。
Here 这里
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;
}
}
Error: The name 'theDates' does not exist in the current context. 错误:名称“ theDates”在当前上下文中不存在。
Sorry if this is something simple or complicated. 很抱歉,这是简单还是复杂。 Any help is appreciated.
任何帮助表示赞赏。
Change 'theDates' in 在中更改“ theDates”
foreach (DateTime date in theDates)
to 'thedates'. 到“日期”。
As mentioned--you also aren't using the correct objects. 如前所述-您也没有使用正确的对象。 You should just create a List of DateTime objects instead of strings.
您应该只创建一个DateTime对象列表,而不是字符串。
List<DateTime> thedates = new List<DateTime>();
thedates.Add(new DateTime{ // Set up values here });
..
..
This is a very basic error and should be found almost everywhere on the internet, the problem is that you are searching with your foreach
loop in a list
called theDates
, that doesn't exists in your application. 这是一个非常基本的错误,应该在Internet上几乎所有地方都可以找到,问题在于您正在使用名为
theDates
的list
foreach
循环进行搜索,该list
在您的应用程序中不存在。
You declared the list
: thedates
at the top of your application and you want to use theDates
, you could rename thedates
to theDates
or just change theDates
to thedates
in your foreach loop. 你声明的
list
: thedates
在你的应用程序的顶部,并要使用theDates
,你可以重命名thedates
到theDates
或者只是改变theDates
到thedates
在你的foreach循环。
You should also change your List<string>
to a List<DateTime>
. 您还应该将
List<string>
更改为List<DateTime>
。
The list<DateTime>
will be filled as follow: 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));
Remember: c# is a case sensitive language. 请记住:c#是区分大小写的语言。
I think the cleanest way is to do a simple LINQ query. 我认为最干净的方法是执行简单的LINQ查询。 I just moved your ticks math into the select statement then tack on a call to
Min()
to get the smallest element in the result set. 我只是将滴答数学移到了select语句中,然后继续调用
Min()
以获取结果集中最小的元素。
closetDate = myDates.Select(Math.Abs(x => x.Ticks - fileDate.Ticks)).Min()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.