/// <summary> /// Get connected nodes for node specified (directed) /// </summary> /// <param name="node">node to search for</param> /// <returns>list of connected nodes</returns> public IReadOnlyList <TNode> GetConnectedNodes(TNode node) { var list = _edges.Values .Where(x => KeyCompare.Equals(x.FromNodeKey, node.Key)) .Join(_nodes.Values, x => x.ToNodeKey, x => x.Key, (o, i) => i) .ToList(); return(list); }
/// <summary> /// Return list of nodes by key(s) /// </summary> /// <param name="nodeKeys">list of node keys</param> /// <returns>nodes matching set</returns> public IReadOnlyList <TNode> FindNodesByKey(IEnumerable <TKey> nodeKeys) { if (nodeKeys == null || !nodeKeys.Any()) { return(new List <TNode>()); } return(Nodes.Values .Where(x => nodeKeys.Any(y => KeyCompare.Equals(x.Key, y))) .ToList()); }
/// <summary> /// Remove node, will remove all edges associated /// </summary> /// <param name="nodeKey"></param> /// <returns></returns> public GraphMap <TKey, TNode, TEdge> RemoveNode(TKey nodeKey) { // Remove edges associated with node _edges.Values .Where(x => KeyCompare.Equals(x.FromNodeKey, nodeKey) || KeyCompare.Equals(x.ToNodeKey, nodeKey)) .Select(x => x.Key) .ToList() .ForEach(x => _edges.Remove(x)); _nodes.Remove(nodeKey); return(this); }
/// <summary> /// Remove edge /// </summary> /// <param name="fromNodeKey">from node key</param> /// <param name="toNodeKey">to node key</param> /// <returns></returns> public GraphMap <TKey, TNode, TEdge> RemoveEdge(TKey fromNodeKey, TKey toNodeKey) { Guid?edgeKey = _edges.Values .Where(x => KeyCompare.Equals(x.FromNodeKey, fromNodeKey) && KeyCompare.Equals(x.ToNodeKey, toNodeKey)) .Select(x => x.Key) .FirstOrDefault(); if (edgeKey != null) { _edges.Remove((Guid)edgeKey); } return(this); }
/// <summary> /// Test edge and return error message /// </summary> /// <param name="edge"></param> /// <returns>error message</returns> private string TestEdge(TEdge edge) { if (!_nodes.ContainsKey(edge.FromNodeKey)) { return($"Parent {edge.FromNodeKey} is not found in nodes"); } if (!_nodes.ContainsKey(edge.ToNodeKey)) { return($"Child {edge.ToNodeKey} is not found in nodes"); } if (KeyCompare.Equals(edge.FromNodeKey, edge.ToNodeKey)) { return($"From node {edge.FromNodeKey} cannot be the same as the to {edge.ToNodeKey}."); } return(null); }