9

我有一个 LinkedList 用于跟踪发送到此类的连续数字。(我最终想找到丢失的数字)。

我现在需要使用方法range.AddAfter(recentNode,someNewNode),但我不能通过强制转换来做到这一点。我错过了什么?

class ContiguousData 
{
    LinkedList<ContiguousDataValue> ranges = new LinkedList<ContiguousDataValue>();

    public void AddValue(int val)
    {
        LinkedListNode<ContiguousDataValue> recentNode = null;

        foreach (var range in ranges)
        {
            if (val > range.UpperInt)
            {
                if (val == range.UpperInt + 1)
                    range.UpperInt = val;
                else
                {
                    if (recentNode == null)
                        ranges.AddFirst(new ContiguousDataValue() { UpperInt = val, LowerInt = val });
                    else
                        ranges.AddAfter(recentNode, new ContiguousDataValue() { UpperInt = val, LowerInt = val });
                }
                break;
            }
            else if (val < range.LowerInt)
            {
                if (val == range.LowerInt - 1)
                    range.LowerInt = val;
                else
                {
                    // do  more logic (incomplete)
                }
            }

           // Compiler error
            recentNode = (LinkedListNode<ContiguousDataValue>)range;
        }

        if (ranges.Count == 0)
        {
            ranges.AddFirst(new ContiguousDataValue() { UpperInt = val, LowerInt = val });
            return;
        }
    }

    internal class ContiguousDataValue
    {
        public int UpperInt { get; set; }
        public int LowerInt { get; set; }
    }
}

由于强制转换不起作用,我如何转换range为 a LinkedListNode<T>

4

1 回答 1

12

我想你正在寻找;

var ranges = new LinkedList<ContiguousDataValue>();

for (var recentNode = ranges.First;
     recentNode != null;
     recentNode = recentNode.Next)
{
  var range = recentNode.Value; 
  ranges.AddAfter(recentNode,someNewNode);
}
于 2012-05-13T05:18:58.477 回答