Pathfinding Issue casing Ienumerable for Nodes

Hi I am working on pathfinding and having some issues with dealing with ienumerables which handle my neighbour cells. I have a gridcell Class which has below

public interface IHasNeighbours
{
    IEnumerable<GridCell> Neighbours { get; }
}

public class GridCell:IHasNeighbours
{
    public bool walkable = true; 
    public GridManager.Point position;
    public IEnumerable<GridCell> AllNeighbours { get; set; }
    public IEnumerable<GridCell> Neighbours {
        get {
            FindNeighbours ();
            return AllNeighbours.Where (o => o.walkable);
        }
    }

I have a Searchnode Class which is used by the pathfinder

public class SearchNode : GridCell
{
    // Location on the map
    public GridManager.Point Position;

    // A reference to the node that transfered this node to
    // the open list.
    public SearchNode Parent;

    // Provides an easy way to check if this node
    // is in the open list.
    public bool InOpenList;

    // Provides an easy way to check if this node
    // is in the closed list.
    public bool InClosedList;

    // The approximate distance from the start node to the
    // goal node if the path goes through this node. (F)
    public float DistanceToGoal;
    
    // Distance traveled from the spawn point. (G)
    public float DistanceTraveled;	
}

The Problem I have is Part of the pathfinder script below

IEnumerable<SearchNode> neighs = currentNode.Neighbours.Cast<SearchNode> ();
for (int i = 0; i < neighs.Count(); i++) {
    SearchNode neighbor = neighs.ToList () *;*

I get the error
InvalidCastException: Cannot cast from source type to destination type.
I need to cast the neigbour has a type so i can .tolist to get a list of the gridcells that are neighbours but i dont know how to cast the neighbours to a searchnode ienumerable.

Beside the fact that this code is not very efficient, the Linq function Cast<> doesn’t cast the type itself. See this [stackoverflow question][1]. Linq and lambda expresions comes in quite handy, but it’s also very easy to write very very uneffective code which is usually not acceptable in games.

It seems you want to iterate through the enumeration, so you can either call MoveNext yourself, or convert it once to a List before the for loop. Just let the type be gridCell, you can cast it inside your loop.

Something like that should work:

List<GridCell> neighs = currentNode.Neighbours.ToList();
for (int i = 0; i < neighs.Count(); i++) {
    SearchNode neighbor = (SearchNode)neighs*;*

[1]: c# - Why Enumerable.Cast raises an InvalidCastException? - Stack Overflow