CSharp examples for System:Array Operation
Replace element in an array
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; using System;//from ww w . j ava 2s.c o m public class Main{ internal static T[] ReplaceAt<T>(this T[] array, int position, int length, T[] items) { return InsertAt(RemoveAt(array, position, length), position, items); } internal static T[] ReplaceAt<T>(this T[] array, int position, T item) { T[] newArray = new T[array.Length]; Array.Copy(array, newArray, array.Length); newArray[position] = item; return newArray; } internal static T[] Copy<T>(this T[] array, int start, int length) { // It's ok for 'start' to equal 'array.Length'. In that case you'll // just get an empty array back. Debug.Assert(start >= 0); Debug.Assert(start <= array.Length); if (start + length > array.Length) { length = array.Length - start; } T[] newArray = new T[length]; Array.Copy(array, start, newArray, 0, length); return newArray; } internal static T[] InsertAt<T>(this T[] array, int position, T item) { T[] newArray = new T[array.Length + 1]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < array.Length) { Array.Copy(array, position, newArray, position + 1, array.Length - position); } newArray[position] = item; return newArray; } internal static T[] InsertAt<T>(this T[] array, int position, T[] items) { T[] newArray = new T[array.Length + items.Length]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < array.Length) { Array.Copy(array, position, newArray, position + items.Length, array.Length - position); } items.CopyTo(newArray, position); return newArray; } internal static T[] RemoveAt<T>(this T[] array, int position, int length) { if (position + length > array.Length) { length = array.Length - position; } T[] newArray = new T[array.Length - length]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < newArray.Length) { Array.Copy(array, position + length, newArray, position, newArray.Length - position); } return newArray; } }