Advertisement
Schnuk

Untitled

Feb 14th, 2021
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace TodoApplication
  5. {
  6. public class ListModel<TItem>
  7. {
  8. public List<TItem> Items { get; }
  9. public int Limit;
  10. public LimitedSizeStack<Tuple<string, TItem, int>> Stack;
  11. private string commandAddName;
  12. private string commandRemoveName;
  13.  
  14. public ListModel(int limit)
  15. {
  16. Items = new List<TItem>();
  17. Limit = limit;
  18. Stack = new LimitedSizeStack<Tuple<string, TItem, int>>(limit);
  19. commandAddName = "AddItem";
  20. commandRemoveName = "RemoveItem";
  21. }
  22.  
  23. public void AddItem(TItem item)
  24. {
  25. Items.Add(item);
  26. Stack.Push(Tuple.Create(commandAddName, item, Items.Count));
  27. }
  28.  
  29. public void RemoveItem(int index)
  30. {
  31. Items.RemoveAt(index);
  32. Stack.Push(Tuple.Create(commandRemoveName, Items[index], index));
  33. }
  34.  
  35. public bool CanUndo()
  36. {
  37. return Stack.Count > 0;
  38. }
  39.  
  40. public void Undo()
  41. {
  42. if (CanUndo())
  43. {
  44. Tuple<string, TItem, int> tuple = Stack.Pop();
  45. string command = tuple.Item1;
  46. TItem stringValue = tuple.Item2;
  47. int index = tuple.Item3;
  48. if (command.Equals(commandAddName))
  49. Items.RemoveAt(index);
  50. if (command.Equals(commandRemoveName))
  51. {
  52. if (index == Items.Count)
  53. Items.Add(stringValue);
  54. else
  55. Items.Insert(index, stringValue);
  56. }
  57. }
  58. }
  59. }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement