Reputation: 3531
I am extending the C# double linked list as a means of creating a custom data structure for a rule engine algorithm I am working on. Unfortunately, the elements in the linked list after instantiation are never actually linked:
public abstract class DependencyTree<TTreeLeaf,TTreeLeafNode>
: LinkedList<LinkedListNode<TTreeLeaf>>
where TTreeLeaf : DependencyTreeLeaf
where TTreeLeafNode : DependencyTreeLeafNode
{
#region Constructors
public DependencyTree(ICollection<TTreeLeaf> leaves)
{
foreach (var leaf in leaves)
{
AddLast(new LinkedListNode<TTreeLeaf>(leaf));
}
var y = this.Where(node => node.Next != null || node.Previous != null).Count();
Console.WriteLine(y.ToString());
}
#endregion Constructors
The above always returns 0, no matter how many Leaves I pass in.
What is the correct way to insure that my leaves are actually linked? I'd rather not roll yet another custom data structure when .NET already has it available. Any tips are much appreciated.
*****EDIT*****
//Addition of DependencyLeaf definition
public abstract class DependencyTreeLeaf
: LinkedList<LinkedListNode<DependencyTreeLeafNode>>
{
#region Constructors
public DependencyTreeLeaf(IEnumerable<DependencyTreeLeafNode> leafNodes, DependencyState siblingDependency = DependencyState.Unset, IEnumerable<DependencyTreeLeaf> children = null, DependencyState childDependency = DependencyState.Unset)
{
foreach (var leaf in leafNodes)
{
AddLast(new LinkedListNode<DependencyTreeLeafNode>(leaf));
}
if (children != null)
{
Children = new LinkedList<LinkedListNode<DependencyTreeLeaf>>();
foreach (var childLeaf in children)
{
Children.AddLast(new LinkedListNode<DependencyTreeLeaf>(childLeaf));
}
}
SiblingForwardDependency = siblingDependency;
ChildDownwardDependency = childDependency;
}
}
Upvotes: 2
Views: 227
Reputation: 44288
you are adding your own linkedlist nodes, you don't need to do this, the linked list will do this. You are adding those LinkedListNode
s into the actual LinkedListNode
s, hence, your ones don't have any previous or next being maintained. However, the problem you are facing is the IEnumerable will iterate over TTreeLeaf
and not nodes.
If you want to iterate over the Nodes themselves then you need something like :-
public class DependencyTree<TTreeLeaf, TTreeLeafNode>
: LinkedList<TTreeLeaf>
where TTreeLeaf : DependencyTreeLeaf
where TTreeLeafNode : DependencyTreeLeafNode
{
public DependencyTree(ICollection<TTreeLeaf> leaves)
{
foreach (var leaf in leaves)
{
AddLast(leaf);
}
var y = this.Nodes().Count(node => node.Next != null || node.Previous != null);
Console.WriteLine(y.ToString());
}
public IEnumerable<LinkedListNode<TTreeLeaf>> Nodes()
{
var node = this.First;
while (node != null)
{
yield return node;
node = node.Next;
}
}
}
you can of course just go this.Count();
Upvotes: 2