开发者

c# linkedlist how to get the the element that is before the last element

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 ?

my code like look like:

 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);


You can get the last node via LinkedList<T>.Last

// list is LinkedList<T> for some T
var last = list.Last;

and the penultimate node via LinkedListNode<T>.Previous

var penultimate = last.Previous; // or list.Last.Previous;

Note that this is a LinkedListNode<T> and you need to use the LinkedListNode<T>.Value property get the underlying instance of T.

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).


@Haim, you may want to check out Krill Osenkov's Undo Framework. It makes undo/redo very easy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜