-
Notifications
You must be signed in to change notification settings - Fork 7
/
UniqueList.cs
134 lines (115 loc) · 2.87 KB
/
UniqueList.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Voxel_Fortress
{
class UniqueList<T> : IList<T>
{
private List<T> _list = new List<T>();
private Dictionary<T, int> _indices = new Dictionary<T, int>();
public T this[int index]
{
get
{
return _list[index];
}
set
{
//We cannot have duplicate values.
if (Contains(value))
return;
//Otherwise changing the value at any index is fine.
_list[index] = value;
}
}
private void RebuildIndices()
{
_indices.Clear();
for(int i = 0; i < _list.Count; i++)
{
_indices[_list[i]] = i;
}
}
public int Count
{
get
{
return _list.Count;
}
}
public bool IsReadOnly
{
get
{
return ((IList<T>)_list).IsReadOnly;
}
}
public int IndexOf(T item)
{
if (Contains(item))
return _indices[item];
else
return -1;
}
public void Add(T item)
{
if (Contains(item))
return;
int itemIndex = _list.Count;
_list.Add(item);
_indices[item] = itemIndex;
}
public void Clear()
{
_list.Clear();
_indices.Clear();
}
public bool Contains(T item)
{
return _indices.ContainsKey(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_list).GetEnumerator();
}
public void Insert(int index, T item)
{
((IList<T>)_list).Insert(index, item);
RebuildIndices();
}
public void RemoveAt(int index)
{
((IList<T>)_list).RemoveAt(index);
RebuildIndices();
}
public bool Remove(T item)
{
int index = IndexOf(item);
if (index < 0)
return false;
RemoveAt(index);
return true;
}
public int IndexAdd(T item)
{
int index = IndexOf(item);
if(index < 0)
{
index = _list.Count;
_list.Add(item);
_indices[item] = index;
}
return index;
}
}
}