Exemplo n.º 1
0
        /// <summary>
        /// Determines whether this collection contains the same count of the same elements as the specified collection.
        /// </summary>
        /// <param name="other">The collection to check this collection against.</param>
        /// <returns>True if both collections contain the same count of the same elements; otherwise false.</returns>
        public bool ContainsSameCountAs(CountingCollection <T> other)
        {
            Contracts.Requires.That(other != null);

            // this is just an optimization
            if (this == other)
            {
                return(true);
            }

            // This is both an optimization and ensures that both collections have the same set
            // of KeyValuePairs given the foreach loop below. Without this check the foreach below
            // would enumerate each KeyValuePair in this collection, but the other could contain
            // more that we don't check.
            if (other.Count != this.Count)
            {
                return(false);
            }

            foreach (var pair in this.countPerItem)
            {
                int countOfItem;
                if (other.countPerItem.TryGetValue(pair.Key, out countOfItem))
                {
                    // check if the count of the other collection's entry matches this collection's current entry count
                    if (countOfItem != pair.Value)
                    {
                        return(false);
                    }
                }
                else
                {
                    // the other collection doesn't contain an entry to match this collection's current entry
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Subtracts the counts of items from the other collection from this collection.
        /// </summary>
        /// <param name="other">The other collection to subtract from this collection.</param>
        public void SubtractCountFrom(CountingCollection <T> other)
        {
            Contracts.Requires.That(other != null);

            foreach (KeyValuePair <T, int> entry in other.countPerItem)
            {
                // if this collection contains the item then subtract from it
                int count;
                if (this.countPerItem.TryGetValue(entry.Key, out count))
                {
                    // this collection's item count equals itself minus the other collection's item count
                    count -= entry.Value;

                    if (count >= 1)
                    {
                        this.countPerItem[entry.Key] = count;
                    }
                    else
                    {
                        this.countPerItem.Remove(entry.Key);
                    }
                }
            }
        }