Map and add all elements of the collection into the source collection. Using the given delegate to transform elements. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Map and add all elements of the collection into the source collection. Using the given delegate to transform elements.

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System;/*  w  w w  .  j a va 2s.  c om*/

public class Main{
        /// <summary>
        /// Map and add all elements of the collection into the source collection.
        /// Using the given delegate to transform elements.
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TAnother"></typeparam>
        /// <param name="source"></param>
        /// <param name="collection"></param>
        /// <param name="transform"></param>
        /// <exception cref="ArgumentNullException">source, collection or transform is null.</exception>
        public static void AddRange<TSource, TAnother>(this ICollection<TSource> source,
            IEnumerable<TAnother> collection, Func<TAnother, TSource> transform)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            if (collection == null)
                throw new ArgumentNullException(nameof(collection));

            if (transform == null)
                throw new ArgumentNullException(nameof(transform));

            foreach (var item in collection)
            {
                source.Add(transform(item));
            }
        }
        /// <summary>
        /// Add all elements of the collection into the source collection.
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <param name="source"></param>
        /// <param name="collection"></param>
        /// <exception cref="ArgumentNullException">source or collection is null.</exception>
        public static void AddRange<TElement>(this ICollection<TElement> source, IEnumerable<TElement> collection)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            if (collection == null)
                throw new ArgumentNullException(nameof(collection));

            foreach (var item in collection)
            {
                source.Add(item);
            }
        }
}

Related Tutorials