Beispiel #1
0
        /// <summary>
        /// Replaces the items in the fromList collection that
        /// are present in the oldItems collection with the items
        /// in the newItems collection.
        /// </summary>
        /// <param name="fromList">The list to have items replaced.</param>
        /// <param name="oldItems">The items in the fromList to be replaced.</param>
        /// <param name="newItems">The items to replace the oldItems collection.</param>
        public static void ReplaceRange(
            this IList fromList, IEnumerable oldItems, IEnumerable newItems)
        {
            AssertArg.IsNotNull(fromList, nameof(fromList));
            AssertArg.IsNotNull(oldItems, nameof(oldItems));
            AssertArg.IsNotNull(newItems, nameof(newItems));

            IRangeOperations collection = fromList as IRangeOperations;

            if (collection != null)
            {
                collection.ReplaceRange(oldItems, newItems);
                return;
            }

            var  suspendableList = fromList as ISuspendChangeNotification;
            bool wasSuspended    = false;

            try
            {
                if (suspendableList != null)
                {
                    wasSuspended = suspendableList.ChangeNotificationSuspended;
                    suspendableList.ChangeNotificationSuspended = true;
                }

                int startIndex = fromList.Count - 1;
                foreach (var item in oldItems)
                {
                    int index = fromList.IndexOf(item);
                    if (index < startIndex)
                    {
                        startIndex = index;
                    }

                    fromList.Remove(item);
                }

                if (startIndex < 0)
                {
                    foreach (var item in newItems)
                    {
                        fromList.Add(item);
                    }

                    return;
                }

                int newIndex = startIndex;

                foreach (var item in newItems)
                {
                    fromList.Insert(newIndex, item);
                    newIndex++;
                }
            }
            finally
            {
                if (suspendableList != null && !wasSuspended)
                {
                    try
                    {
                        suspendableList.ChangeNotificationSuspended = false;
                    }
                    catch (Exception)
                    {
                        /* Suppress. */
                    }
                }
            }
        }