Can you help me with step by step logic that I need to get a direction on the same train line. with already having common train line with functions Next and Previous.
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];
}
And my function where I look for direction.
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";
}
It looks like you are trying to "visit the stations along commonLine
", starting at the from
station.
The loop you have started is a valid start to that end; you need a variable to store the station you are currently visiting. Maybe the current variable name Final
is a bit confusing to yourself here, because it is not the "final" station of the line, just the one you are currently visiting.
Therefore, let's name the variable currentStation
. Then, you want to go to the next station until you have found to
(and thereby know the direction), or until you have reached the end of the line:
var currentStation = from;
while (currentStation != null)
{
if (currentStation == to)
{
return "next";
}
currentStation = commonLine.Next(currentStation);
}
Now, this checks whether to
is "ahead". If it wasn't, you can proceed to checking whether it can be found in the other direction, again starting at from
:
currentStation = from;
while (currentStation != null)
{
if (currentStation == to)
{
return "previous";
}
currentStation = commonLine.Previous(currentStation);
}
If this loop doesn't find to
either, apparently to
is not on the line. Treat this case according to your preference.
Some remarks:
Line
object already has the stations in an indexed list. Therefore, a simpler way of achieving your goal might be to just determine the indices of the from
and to
stations on commonLine
and compare which one is greater than the other.