Adds all of the elements of the "c" collection to the "target" collection. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Adds all of the elements of the "c" collection to the "target" collection.

Demo Code


using System.IO;//from   w  w w .ja  va  2  s  .  c  om
using System;

public class Main{
        /// <summary>
        /// Adds all of the elements of the "c" collection to the "target" collection.
        /// </summary>
        /// <param name="target">Collection where the new elements will be added.</param>
        /// <param name="c">Collection whose elements will be added.</param>
        /// <returns>Returns true if at least one element was added, false otherwise.</returns>
        public static bool AddAll(System.Collections.ICollection target, System.Collections.ICollection c)
        {
            System.Collections.IEnumerator e = new System.Collections.ArrayList(c).GetEnumerator();
            bool added = false;

            //Reflection. Invoke "addAll" method for proprietary classes
            System.Reflection.MethodInfo method;
            try
            {
                method = target.GetType().GetMethod("addAll");

                if (method != null)
                    added = (bool)method.Invoke(target, new Object[] { c });
                else
                {
                    method = target.GetType().GetMethod("Add");
                    while (e.MoveNext() == true)
                    {
                        bool tempBAdded = (int)method.Invoke(target, new Object[] { e.Current }) >= 0;
                        added = added ? added : tempBAdded;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return added;
        }
}

Related Tutorials