Looping IEnumerable
How do I get a specific index or loop through this data structure?
public class Path<TNode> : IEnumerable<TNode>
{
public TNode LastStep { get; private set; }
public Path<TNode> PreviousSteps { get; private set; }
public double TotalCost { get; private set; }
private Path(TNode lastStep, Path<TNode> previousSteps, double totalCost)
{
LastStep = lastStep;
PreviousSteps = previousSteps;
TotalCost = totalCost;
}
public Path(TNode start) : this(start, null, 0) { }
public Path<TNode> AddStep(TNode step, double stepCost)
{
return new Path<TNode>(step, this, TotalCost + stepCost);
}
public IEnumerator<TNode> GetEnumerator()
{
for (Path<TNode> p = this; p != null; p = p.PreviousSteps)
yield return p.LastStep;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
It is used as a graph for an A* algorithm. I want to do 2 things with this data structure:
- Generate a开发者_如何学Python graph (add nodes and their children)
- Be able to traverse it and find a node and get its specific index like:
Path<Vector2> node;
then be able to donode[0]
.
Well you can loop through it just with a foreach loop:
foreach (Vector2 node in path)
{
...
}
Admittedly this looks like it will iterate in a reverse order - if you want to reverse it, you could just use LINQ like this:
foreach (Vector2 node in path.Reverse())
You can do that because you've implemented IEnumerable<T>
. To be able to access it by index is rather trickier... you won't be able to do that in a particularly efficient way as far as I can tell.
Again, you can use LINQ to fake it - but that will just iterate over the nodes until it reaches the right element:
Vector2 node = path.ElementAt(2); // Or whatever
精彩评论