我正在扩展C#双链表,作为为我正在处理的规则引擎算法创建自定义数据结构的一种方法。不幸的是,实例化后链表中的元素实际上从未实际链接过:
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
无论我传了多少叶,上面总是会返回0。
确保我的树叶真正联系起来的正确方法是什么?当.NET已经可用时,我宁愿不再滚动另一个自定义数据结构。任何提示都非常感谢。
***** 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;
}
}
答案 0 :(得分:2)
您正在添加自己的链接列表节点,您不需要这样做,链接列表将执行此操作。您正在将LinkedListNode
添加到实际的LinkedListNode
中,因此,您的那些没有任何上一个或下一个维护。但是,您遇到的问题是IEnumerable将迭代TTreeLeaf
而不是节点。
如果您想迭代节点本身,那么您需要以下内容: -
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;
}
}
}
你当然可以去this.Count();