Here's an implementation that incorporates the IMergable interface and provides a more flexible approach to merging nodes:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
// Interface for nodes that can be merged
public interface IMergable<T> where T : IMergable<T>
{
/// <summary>
/// Merges the current node with another node of the same type
/// </summary>
/// <param name="other">The node to merge into this one</param>
/// <returns>The merged node</returns>
T Merge(T other);
/// <summary>
/// Determines if this node is equivalent to another node
/// </summary>
/// <param name="other">The node to compare</param>
/// <returns>True if nodes are considered equivalent, false otherwise</returns>
bool IsEquivalentTo(T other);
}
public class ThreadSafeGraph<TNode, TEdge>
where TNode : class, IMergable<TNode>, IEquatable<TNode>
{
// Thread-safe collections to store graph data
private readonly ConcurrentDictionary<TNode, ConcurrentHashSet<TNode>> _children
= new(new NodeEqualityComparer<TNode>());
private readonly ConcurrentDictionary<TNode, ConcurrentHashSet<TNode>> _parents
= new(new NodeEqualityComparer<TNode>());
private readonly ConcurrentDictionary<TNode, ConcurrentHashSet<TEdge>> _edges
= new(new NodeEqualityComparer<TNode>());
// Custom equality comparer to handle node equivalence
private class NodeEqualityComparer<T> : IEqualityComparer<T>
where T : IMergable<T>, IEquatable<T>
{
public bool Equals(T? x, T? y)
{
if (ReferenceEquals(x, y)) return true;
if (x is null || y is null) return false;
return x.IsEquivalentTo(y);
}
public int GetHashCode(T obj)
{
// Implement a consistent hash code based on node's unique characteristics
return obj.GetHashCode();
}
}
// Thread-safe set implementation
private class ConcurrentHashSet<T> : ConcurrentDictionary<T, byte>
{
public bool TryAdd(T item) => TryAdd(item, 0);
public bool TryRemove(T item) => TryRemove(item, out _);
public bool Contains(T item) => ContainsKey(item);
public IEnumerable<T> Items => Keys;
}
/// <summary>
/// Adds or merges a node into the graph
/// </summary>
/// <param name="node">The node to add</param>
/// <returns>The canonical (merged or existing) node</returns>
public TNode AddNode(TNode node)
{
return _children.AddOrUpdate(
node,
// Add new node if not exists
keyNode => {
_parents[keyNode] = new ConcurrentHashSet<TNode>();
_edges[keyNode] = new ConcurrentHashSet<TEdge>();
return keyNode;
},
// Merge if equivalent node exists
(existingNode, _) => {
// Merge the nodes
var mergedNode = existingNode.Merge(node);
// Update references for merged node
UpdateNodeReferences(existingNode, mergedNode);
return mergedNode;
}
);
}
/// <summary>
/// Adds an edge between two nodes
/// </summary>
public void AddEdge(TNode source, TNode target, TEdge edge)
{
// Ensure nodes are in the graph (and potentially merged)
var canonicalSource = AddNode(source);
var canonicalTarget = AddNode(target);
// Add edge and update relationships
_edges[canonicalSource].TryAdd(edge);
_children[canonicalSource].TryAdd(canonicalTarget);
_parents[canonicalTarget].TryAdd(canonicalSource);
}
/// <summary>
/// Updates node references when merging
/// </summary>
private void UpdateNodeReferences(TNode oldNode, TNode newNode)
{
// Update children references
foreach (var child in _children[oldNode].Items)
{
_children[newNode].TryAdd(child);
_parents[child].TryRemove(oldNode);
_parents[child].TryAdd(newNode);
}
// Update parent references
foreach (var parent in _parents[oldNode].Items)
{
_parents[newNode].TryAdd(parent);
_children[parent].TryRemove(oldNode);
_children[parent].TryAdd(newNode);
}
// Transfer edges
foreach (var edge in _edges[oldNode].Items)
{
_edges[newNode].TryAdd(edge);
}
// Remove old node references
_children.TryRemove(oldNode, out _);
_parents.TryRemove(oldNode, out _);
_edges.TryRemove(oldNode, out _);
}
/// <summary>
/// Gets root nodes (nodes with no parents)
/// </summary>
public IEnumerable<TNode> GetRoots()
{
return _parents
.Where(kvp => kvp.Value.Count == 0)
.Select(kvp => kvp.Key);
}
/// <summary>
/// Breadth-first traversal of the graph
/// </summary>
public IEnumerable<TNode> BreadthFirstTraversal()
{
var visited = new ConcurrentDictionary<TNode, byte>(new NodeEqualityComparer<TNode>());
var queue = new ConcurrentQueue<TNode>();
// Start with root nodes
foreach (var root in GetRoots())
{
queue.Enqueue(root);
visited.TryAdd(root, 0);
}
while (queue.TryDequeue(out var current))
{
yield return current;
// Explore children
foreach (var child in _children[current].Items)
{
if (visited.TryAdd(child, 0))
{
queue.Enqueue(child);
}
}
}
}
/// <summary>
/// Depth-first traversal of the graph
/// </summary>
public IEnumerable<TNode> DepthFirstTraversal()
{
var visited = new ConcurrentDictionary<TNode, byte>(new NodeEqualityComparer<TNode>());
foreach (var root in GetRoots())
{
foreach (var node in DepthFirstTraversalRecursive(root, visited))
{
yield return node;
}
}
}
private IEnumerable<TNode> DepthFirstTraversalRecursive(
TNode node,
ConcurrentDictionary<TNode, byte> visited)
{
if (visited.TryAdd(node, 0))
{
yield return node;
foreach (var child in _children[node].Items)
{
foreach (var descendant in DepthFirstTraversalRecursive(child, visited))
{
yield return descendant;
}
}
}
}
}
// Example Usage
public record class MyNode(string Id) : IMergable<MyNode>
{
// Merge implementation
public MyNode Merge(MyNode other)
{
// Custom merge logic - could combine properties, etc.
return new MyNode(Id + "_" + other.Id);
}
// Equivalence check
public bool IsEquivalentTo(MyNode other) => Id == other.Id;
}
public record class MyEdge(string Source, string Target);
class Program
{
static void Main()
{
var graph = new ThreadSafeGraph<MyNode, MyEdge>();
// Create and add nodes
var nodeA = new MyNode("A");
var nodeB = new MyNode("B");
var nodeC = new MyNode("C");
// Add edges
graph.AddEdge(nodeA, nodeB, new MyEdge("A", "B"));
graph.AddEdge(nodeB, nodeC, new MyEdge("B", "C"));
// Demonstrate merging
var duplicateA = new MyNode("A");
var mergedA = graph.AddNode(duplicateA); // Will merge with existing A node
// Traverse the graph
Console.WriteLine("Breadth-First Traversal:");
foreach (var node in graph.BreadthFirstTraversal())
{
Console.WriteLine(node.Id);
}
Console.WriteLine("\nDepth-First Traversal:");
foreach (var node in graph.DepthFirstTraversal())
{
Console.WriteLine(node.Id);
}
}
}
Key Features:
-
IMergable<T> Interface
- Defines two key methods:
Merge(T other): Combines two nodes
IsEquivalentTo(T other): Checks node equivalence
-
Thread Safety
- Uses
ConcurrentDictionary and custom ConcurrentHashSet
- Custom equality comparer handles node merging
-
Flexible Node Merging
- Nodes can define their own merge and equivalence logic
- Automatically updates graph relationships during merge
-
Graph Traversal
- Breadth-first and depth-first traversal methods
- Starts from root nodes (nodes with no parents)
-
Generic Implementation
- Works with any node type implementing
IMergable<T> and IEquatable<T>
- Supports custom edge types
Example Node Implementation:
public record class ComplexNode(
string Id,
List<string> Properties
) : IMergable<ComplexNode>
{
public ComplexNode Merge(ComplexNode other)
{
// Combine properties, remove duplicates
var mergedProperties = Properties
.Concat(other.Properties)
.Distinct()
.ToList();
return this with {
Properties = mergedProperties
};
}
public bool IsEquivalentTo(ComplexNode other) =>
Id == other.Id;
}
Considerations:
- Performance is optimized for concurrent access
- Merge logic is entirely customizable
- Supports complex node and edge types
- Thread-safe graph operations
The implementation provides a robust, flexible graph structure with built-in merging capabilities, suitable for various use cases requiring thread-safe graph manipulation.