-
Notifications
You must be signed in to change notification settings - Fork 4
/
ListDict.cs
72 lines (60 loc) · 1.76 KB
/
ListDict.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
using System;
using System.Collections;
using System.Collections.Generic;
public class ListDict<TKey, TValue> {
public readonly List<TKey> Keys;
public readonly List<TValue> Values;
public int Count { get { return Keys.Count; } }
public ListDict(int capacity = 0) {
Keys = new List<TKey>(capacity);
Values = new List<TValue>(capacity);
}
public void Add(TKey key, TValue value = default(TValue)) {
var index = Keys.IndexOf(key);
if (index < 0) {
Keys.Add(key);
Values.Add(default(TValue));
index = Keys.Count - 1;
}
Values[index] = value;
}
public TValue GetOrDefault(TKey key) {
var index = Keys.IndexOf(key);
return index >= 0 && index < Count ? Values[index] : default(TValue);
}
public bool Remove(TKey key) {
return RemoveAt(Keys.IndexOf(key));
}
public int RemoveAll(TKey key) {
var removedCount = 0;
var nextIndex = Keys.IndexOf(key);
while (nextIndex >= 0) {
RemoveAt(nextIndex);
removedCount++;
nextIndex = Keys.IndexOf(key);
}
return removedCount;
}
public bool RemoveAt(int index) {
if (index < 0 || index >= Count) {
return false;
}
Keys.RemoveAt(index);
Values.RemoveAt(index);
return true;
}
public void Clear() {
Keys.Clear();
Values.Clear();
}
public bool ContainsKey(TKey key) {
return Keys.IndexOf(key) >= 0;
}
public TValue this[TKey key] {
get { return Values[Keys.IndexOf(key)]; }
set { Add(key, value); }
}
public override string ToString() {
return string.Format("Count = {0}", Count);
}
}