Ejemplo n.º 1
0
        /// <summary>Inserts the elements of a collection into the list at the specified index.</summary>
        /// <param name="index">The zero-based index at which the new elements should be inserted.</param>
        /// <param name="elements">
        ///     The collection whose elements should be inserted into the list.
        ///     The collection itself cannot be null, but it can contain elements that are null,
        ///     if type <typeparamref name="T" /> is a reference type.
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">index is less than 0 -or- index is greater than Count.</exception>
        public void InsertRange(int index, [NotNull] IEnumerable <T> elements)
        {
            Check.NotNull(elements)
            .InRange(index, 0, Count, "index is less than 0 -or- index is greater than Count.",
                     nameof(index));

            // First call the pre-event if needed, enumerating sequence in process:
            var             success       = true;
            IEnumerable <T> fixedElements = null;
            var             beforeRangeAdditionHandler = Volatile.Read(ref BeforeRangeAddition);

            if (EventsEnabled && (beforeRangeAdditionHandler != null))
            {
                // ReSharper disable PossibleMultipleEnumeration
                fixedElements = elements as ICollection <T> ?? elements.ToArray();
                success       = beforeRangeAdditionHandler(this, index, (ICollection <T>)fixedElements);
            }

            if (success)
            {
                // Enumerated sequence will be null if pre-event was not called, since no enumeration was done.
                if (fixedElements == null)
                {
                    fixedElements = elements;
                }

                // ReSharper enable PossibleMultipleEnumeration
                var countBefore = Count;
                _list.InsertRange(index, fixedElements);

                var addedTotal = Count - countBefore;
                if (EventsEnabled && (addedTotal > 0))
                {
                    RangeAdded.Call(this, index, addedTotal);
                }
            }
        }