Ejemplo n.º 1
0
        public bool TryAppend(T item, out SortedListSlim <T> newSortedList)
        {
            newSortedList = null;
            var pair  = new KeyValuePair <int, T>(m_codeGenerator.GetHashCode(item), item);
            var index = m_sortedList.BinarySearch(pair, _pairComparer);

            if (index >= 0)
            {
                // 有可能是哈希冲突
                if (IsExists(pair, ref index))
                {
                    return(false);
                }

                index = ~index;
            }

            var largerIndex = ~index;
            var newList     = new List <KeyValuePair <int, T> >(m_sortedList.Count + 1);

            if (largerIndex > 0)
            {
                newList.AddRange(m_sortedList.Take(largerIndex));
            }

            newList.Add(pair);

            if (largerIndex < m_sortedList.Count)
            {
                newList.AddRange(m_sortedList.Skip(largerIndex));
            }

            newSortedList = new SortedListSlim <T>(newList, m_valueComparer, m_codeGenerator);
            return(true);
        }
Ejemplo n.º 2
0
        public bool TryRemove(T item, out SortedListSlim <T> newSortedList)
        {
            newSortedList = null;
            var pair  = new KeyValuePair <int, T>(m_codeGenerator.GetHashCode(item), item);
            var index = m_sortedList.BinarySearch(pair, _pairComparer);

            if (index < 0)
            {
                return(false);
            }

            // 有可能是哈希冲突
            if (!IsExists(pair, ref index))
            {
                return(false);
            }

            var newList = new List <KeyValuePair <int, T> >(Math.Max(1, m_sortedList.Count - 1));

            if (index > 0)
            {
                newList.AddRange(m_sortedList.Take(index));
            }

            index++;

            if (index < m_sortedList.Count)
            {
                newList.AddRange(m_sortedList.Skip(index));
            }

            newSortedList = new SortedListSlim <T>(newList, m_valueComparer, m_codeGenerator);
            return(true);
        }