expand array on specified number of elements - CSharp System

CSharp examples for System:Array Split

Description

expand array on specified number of elements

Demo Code


using System.Text;
using System.Runtime.InteropServices;
using System.Linq;
using System.Collections.Generic;
using System;/*w  w  w.  j av a 2s.  c  o  m*/

public class Main{
        /// <summary>
      /// expand array on specified number of elements
      /// </summary>
      /// <typeparam name="T">type of elements</typeparam>
      /// <param name="array">array to be expanded</param>
      /// <param name="capacity">number of elements that will be added to new array</param>
      /// <returns>
      /// if capacity is lower or equal zero the array passsed as argumentt will be returned.
      /// otherwise returns new array with copy of elements from the array passed as argument, 
      /// and padded with number of elements specified by capacity argument
      /// </returns>
      public static T[] Expand<T>(this T[] array, int capacity) {
         if (capacity <= 0) {
            return array;
         }
         if (array == null) {
            return new T[capacity];
         }
         var newArray = new T[array.Length + capacity];
         array.CopyTo(newArray, 0); 
         Array.Copy(array, newArray, array.Length);
         return newArray;
      }
        /// <summary>
      /// projects each element of an array into a new form
      /// </summary>
      /// <typeparam name="TSrc">the type of the elements of source array</typeparam>
      /// <typeparam name="TRes">the type of the value returned by selector</typeparam>
      /// <param name="array">an array of values to invoke a transform function on</param>
      /// <param name="selector">a transform function to apply to each element</param>
      /// <returns>
      /// an array whose elements are the result of invoking the transform function on each element of source array
      /// </returns>
      public static TRes[] Copy<TSrc, TRes>(this TSrc[] array, Func<TSrc, TRes> selector) {
         if(array == null){
            return null;
         }
         var cnt = array.Length;
         var mappedArray = new TRes[cnt];
         for (int i = 0; i < cnt; ++i) {
            mappedArray[i] = selector(array[i]);
         }
         return mappedArray;
      }
}

Related Tutorials