问题
您需要链表数据结构这样就可以很容易地添加和删除元素
解决方案
使用泛型LinkedList<T>类下面思路方法创建了个LinkedList<T>类并往链表对象中添加节点然后使用了几种思路方法从链表节点中获得信息
public void UseLinkedList
{
// 创建个LinkedList 对象.
LinkedList<TodoItem> todoList = LinkedList<TodoItem>;
// 创建添加到链表内TodoItem对象.
TodoItem i1 = TodoItem("pa door", "Should be done third");
TodoItem i2 = TodoItem("buy door", "Should be done first");
TodoItem i3 = TodoItem("assemble door", "Should be done second");
TodoItem i4 = TodoItem("hang door", "Should be done last");
// 添加项目.
todoList.AddFirst(i1);
todoList.AddFirst(i2);
todoList.AddBefore(todoList.Find(i1), i3);
todoList.AddAfter(todoList.Find(i1), i4);
// 显示所有项目.
foreach (TodoItem tdi in todoList)
{
Console.WriteLine(tdi.Name + " : " + tdi.Comment);
}
// 显示链表内第 2个节点信息
Console.WriteLine("todoList.First.Next.Value.Name " +
todoList.First.Next.Value.Name);
// 显示链表内最后个节点前节点信息.
Console.WriteLine("todoList.Last.Previous.Value.Name " +
todoList.Last.Previous.Value.Name);
}
这个思路方法输出结果如下:
buy door : Should be done first
assemble door : Should be done second
pa door : Should be done third
hang door : Should be done last
todoList.First.Value.Name buy door
todoList.First.Next.Value.Name assemble door
todoList.Last.Previous.Value.Name pa door
下面是TodoItem类它只简单地包含了两个串_name和_comment
public TodoItem
{
public TodoItem( name, comment)
{
_name = name;
_comment = comment;
}
private _name = "";
private _comment = "";
public Name
{
get { (_name); }
{ _name = value; }
}
public Comment
{
get { (_comment); }
{ _comment = value; }
}
}
讨论
LinkedList<T>类在.NET framework中是个双向链表这是链表中每个节点都包含了前节点和后节点指针图4-1演示了这种结构图中每个node代表了个单独LinkedListNode<T>对象
如果表达式中可空类型是个null值则表达式结果为null但如果没有可空类型值为null运算符会把它当成般类型如上例中DBInt为null则Result结果也为null
最新评论