publicboolRemove(T item) { // 取出对应元素在List中的下标位置 int index = -1; if (!m_Dictionary.TryGetValue(item, out index)) returnfalse; // 删除List中该下标元素 RemoveAt(index); returntrue; }
实现以下两个方法以提供foreach遍历
1 2 3 4 5 6 7 8 9
public IEnumerator<T> GetEnumerator() { thrownew System.NotImplementedException(); }
publicvoidInsert(int index, T item) { thrownew NotSupportedException("Random Insertion is semantically invalid, since this structure does not guarantee ordering."); }
public T this[int index] { get { return m_List[index]; } set { T item = m_List[index]; m_Dictionary.Remove(item); m_List[index] = value; m_Dictionary.Add(item, index); } }
RemoveAll:
Predicate<T> match 是一个委托,它表示一个方法或 Lambda 表达式,用来确定是否移除列表中的元素。
publicvoidRemoveAll(Predicate<T> match) { int i = 0; while (i < m_List.Count) { // 判断元素是否匹配传入的委托,匹配则删除 T item = m_List[i]; if (match(item)) Remove(item); else i++; } }
Sort:
对内部列表进行排序,这使得暴露的索引访问器也排序。
但是注意,任何插入或删除都可以再次打乱集合的顺序。
由上面的插入和删除代码可知道,会打乱排序,所以这个容器的排序不是持久化的
1 2 3 4 5 6 7 8 9 10 11
publicvoidSort(Comparison<T> sortLayoutFunction) { // 可能有更好的排序方法,并使得字典的索引保持最新 m_List.Sort(sortLayoutFunction); // 重建字典的索引 for (int i = 0; i < m_List.Count; ++i) { T item = m_List[i]; m_Dictionary[item] = i; } }