如何在同一条火车线上找到方向?

问题描述 投票:0回答:2

您能在逐步路线上帮助我,我需要在同一条火车线上确定方向。已经具有具有下一个和上一个功能的通用火车线。

public IStation Next(IStation s)
{
    if (!_stations.Contains(s))
    {
        throw new ArgumentException();
    }
    var index = _stations.IndexOf(s);
    var isLast = index == _stations.Count -1;
    if (isLast)
    {
        return null;
    }
    return _stations[index + 1];
}

public IStation Previous(IStation s)
{
    if (!_stations.Contains(s))
    {
        throw new ArgumentException();
    }
    var index = _stations.IndexOf(s);
    var isFirst = index == 0;
    if (isFirst)
    {
        return null;
    }
    return _stations[index - 1];
}

还有我寻找方向的功能。

public string GetLineDirectiom(Station from, Station to, Line commonLine)
{
    bool fromNextTo = true;


    //to.Lines.Count();
    //to.ToString();
    var Final = commonLine.Next(from);
    while (Final != null)
    {

    }

    if (fromNextTo)
        return "next";
    else return "previous";
}
c# next directions
2个回答
1
投票

似乎您正在尝试从commonLine电台开始“访问from电台”。

您已经开始的循环是到此为止的有效起点;您需要一个变量来存储您当前正在访问的电台。也许当前的变量名Final在这里会让您感到困惑,因为它不是该行的“最终”站,而只是您当前正在访问的站。

因此,我们将变量命名为currentStation。然后,您想转到下一个站点,直到找到to(从而知道方向),或者直到到达行尾为止:

var currentStation = from;
while (currentStation != null)
{
    if (currentStation == to)
    {
        return "next";
    }
    currentStation = commonLine.Next(currentStation);
}

现在检查to是否在“前面”。如果没有找到,您可以再次从from开始检查是否可以在另一个方向找到它:

currentStation = from;
while (currentStation != null)
{
    if (currentStation == to)
    {
        return "previous";
    }
    currentStation = commonLine.Previous(currentStation);
}

如果此循环也找不到to,则显然to不在线上。根据您的喜好处理这种情况。

一些评论:

  • 将方向指示为“下一个”或“上一个”可能会引起误解。如果确实是行的方向,请考虑“向前”和“向后”之类的事情,因为“下一个”和“上一个”确实暗示列表中直接下一个/上一个元素。
  • 尽管上述工作有效,但我确实注意到您的Line对象已经在索引列表中包含了测站。因此,实现目标的一种更简单的方法可能是只确定fromtocommonLine电台的索引并比较哪个大于另一个。

0
投票

尚不清楚您想做什么,为什么要返回字符串“ next”和“ prev”作为方向,但通常是由两个工作站来获得方向:

© www.soinside.com 2019 - 2024. All rights reserved.