public static void MergeVertices <TVertex, TEdge>(this IMutableBidirectionalGraph <TVertex, TEdge> graph, IEnumerable <TVertex> verticesToMerge, TVertex replacement, Func <TEdge, TVertex, TEdge> mergeInFunc, Func <TVertex, TEdge, TEdge> mergeOutFunc, IEqualityComparer <TVertex> comparer = null, bool checkExistence = false) where TEdge : IEdge <TVertex> { var verticies = (checkExistence ? graph.Vertices.Intersect(verticesToMerge, comparer) : verticesToMerge).ToList(); var allInEdges = verticies.SelectMany(graph.InEdges); var allOutEdges = verticies.SelectMany(graph.OutEdges); var newInEdges = allInEdges.Select(x => mergeInFunc(x, replacement)); var newOutEdges = allOutEdges.Select(x => mergeOutFunc(replacement, x)); verticies.ForEach(x => graph.RemoveVertex(x)); graph.AddVertex(replacement); graph.AddEdgeRange(newInEdges); graph.AddEdgeRange(newOutEdges); }
public static void DeleteVerticesAndMergeEdges <TVertex, TEdge> (this IMutableBidirectionalGraph <TVertex, TEdge> graph, TVertex vertexToDelete, Func <TEdge, TEdge, TEdge> mergeFunc) where TEdge : IEdge <TVertex> { if (graph.IsInEdgesEmpty(vertexToDelete) || graph.IsOutEdgesEmpty(vertexToDelete)) { //simple case graph.RemoveVertex(vertexToDelete); } else { //need to keep connections var newEdges = from e1 in graph.InEdges(vertexToDelete) from e2 in graph.OutEdges(vertexToDelete) select mergeFunc(e1, e2); //create edges var newEdgesList = newEdges.ToList(); graph.AddEdgeRange(newEdgesList); graph.RemoveVertex(vertexToDelete); } }