Concatenate two arrays. - CSharp System

CSharp examples for System:Array Element Add

Description

Concatenate two arrays.

Demo Code


using System.Linq;
using System;//from  www.  j  a v a  2s.  c om

public class Main{
        /// <summary>
        ///     Concatenate two byte arrays.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr1">The first byte array.</param>
        /// <param name="arr2">The second byte array.</param>
        /// <returns>The concatenated byte arrays.</returns>
        /// <exception cref="OverflowException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static T[] ConcatArrays<T>(T[] arr1, T[] arr2)
        {
            checked
            {
                var result = new T[arr1.Length + arr2.Length];
                Buffer.BlockCopy(arr1, 0, result, 0, arr1.Length);
                Buffer.BlockCopy(arr2, 0, result, arr1.Length, arr2.Length);

                return result;
            }
        }
        /// <summary>
        ///     Concatenate the given byte arrays.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arrays">The byte arrays.</param>
        /// <returns>The concatenated byte arrays.</returns>
        /// <exception cref="OverflowException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static T[] ConcatArrays<T>(params T[][] arrays)
        {
            checked
            {
                var result = new T[arrays.Sum(arr => arr.Length)];
                var offset = 0;

                foreach (var arr in arrays)
                {
                    Buffer.BlockCopy(arr, 0, result, offset, arr.Length);
                    offset += arr.Length;
                }

                return result;
            }
        }
}

Related Tutorials