Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace TodoApplication
- {
- public class ListModel<TItem>
- {
- public List<TItem> Items { get; }
- public int Limit;
- public LimitedSizeStack<Tuple<string, TItem, int>> Stack;
- private string commandAddName;
- private string commandRemoveName;
- public ListModel(int limit)
- {
- Items = new List<TItem>();
- Limit = limit;
- Stack = new LimitedSizeStack<Tuple<string, TItem, int>>(limit);
- commandAddName = "AddItem";
- commandRemoveName = "RemoveItem";
- }
- public void AddItem(TItem item)
- {
- Items.Add(item);
- Stack.Push(Tuple.Create(commandAddName, item, Items.Count));
- }
- public void RemoveItem(int index)
- {
- Items.RemoveAt(index);
- Stack.Push(Tuple.Create(commandRemoveName, Items[index], index));
- }
- public bool CanUndo()
- {
- return Stack.Count > 0;
- }
- public void Undo()
- {
- if (CanUndo())
- {
- Tuple<string, TItem, int> tuple = Stack.Pop();
- string command = tuple.Item1;
- TItem stringValue = tuple.Item2;
- int index = tuple.Item3;
- if (command.Equals(commandAddName))
- Items.RemoveAt(index);
- if (command.Equals(commandRemoveName))
- {
- if (index == Items.Count)
- Items.Add(stringValue);
- else
- Items.Insert(index, stringValue);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement