C#链表如何获取最后一个元素之前的元素 [英] c# linkedlist how to get the the element that is before the last element
问题描述
我尝试在我的 Windows 窗体应用程序中实现重做撤消.
i try to implement a redo undo in my windows form application.
我建立了一个链表,链表中的每个输入都是一个类,该类以表格的形式保存所有要素的状态.
i build a linkedlist , every entery of the list is a class that save the state of all the elemnts in the form.
每次单击保存"按钮,将表单元素的最后状态插入此列表.
every click on the save button , insert to this list the last state of the form elements.
当用户单击撤消按钮时,我想获取列表的内容(最后一个之前)并加载它.
when the user click on undo button i want to get the entery of the list (one before the last) and load it.
我不知道从链表中删除元素之前获取此密码的简单方法是什么?
i dont know what is the simple way to get this one before elemnts from the linked list ?
我的代码如下:
public class SaveState {
public int comboBox1;
public int comboBox2;
..........
public SaveState() {
.......
}
}
LinkedList<SaveState> RedoUndo = new LinkedList<SaveState>();
# in save function
var this_state = new SaveState();
this_state = getAllState();
RedoUndo.AddLast(this_state);
# when click undo
var cur_state = new SaveState();
# this lines dont work !!!!!!!!!
int get = RedoUndo.Count - 1;
cur_state = RedoUndo.Find(get);
setAllState(cur_state);
推荐答案
您可以通过 LinkedList< T> ;.最后
You can get the last node via LinkedList<T>.Last
// list is LinkedList<T> for some T
var last = list.Last;
和倒数第二个节点通过 LinkedListNode< T>.上一个代码>
and the penultimate node via LinkedListNode<T>.Previous
var penultimate = last.Previous; // or list.Last.Previous;
请注意,这是 LinkedListNode< T>
,则需要使用 LinkedListNode< T> .Value
属性获取 T
的基础实例.
Note that this is a LinkedListNode<T>
and you need to use the LinkedListNode<T>.Value
property get the underlying instance of T
.
当然,您应该注意检查 list
不为空,并且 list.Last
不为null(如果为空列表),并且 list.Last.Previous
不为null(对于单元素列表).
Of course, you should take care to check that list
is not null, and list.Last
is not null (in the case of an empty list), and that list.Last.Previous
is not null (in the case of a single-element list).
这篇关于C#链表如何获取最后一个元素之前的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!