User Tools

Site Tools


notes:csharp:arrays

Arrays in C#

Creating and Initializing

Creating an array always initializes its elements with default values.

Single-dimensional arrays

// Create an array of three integers.
int[] a = new int[3];
 
// Create and initialize an array (equivalent syntaxes).
int[] a = new int[3] { 1, 2, 3 };
int[] a = new int[] { 1, 2, 3 };
int[] a = { 1, 2, 3 };
 
// An implicitly typed array: have the compiler infer the array type (works for single-dimensional arrays).
var a = new[] { "abc", "def", "ghi" }; // the compiler infers string[]
var a = new[] { 1, 2, 3, 4, 5 }; // the compiler infers int[]
 
// Create an array and populate it with instances of an anonymous type.
var books = new[]
{
    new { Title = "Title1", Author = "Author1" },
    new { Title = "Title2", Author = "Author2" },
    new { Title = "Title3", Author = "Author3" }
};
 
// Create an empty array.
int[] a = new int[0] {};
 
// Create a byte array containing 100 elements.
byte[] a = Enumerable.Repeat((byte)'a', 100).ToArray();

Multidimensional arrays

// Create a two-dimensional array containing 2*3 elements.
int[,] a = new int[2, 3];
 
// Create a three-dimensional array containing 5^3 elements.
int[,,] a = new int[5, 5, 5];
 
// Create and initialize a two-dimensional array int[2,3].
int[,] a = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
 
// Alternative syntax: the 'new' operator and type qualifications can be omitted.
int[,] a = { { 1, 2, 3 }, { 4, 5, 6 } }; // creates int[2,3]
 
// Traverse a two-dimensional array with foreach.
int[,] a = { { 1, 2, 3 }, { 4, 5, 6 } };
foreach (int n in a)  // n = 1,2,3,4,5,6
{
    //...
}
 
// Traverse a two-dimensional array using a for loop.
// The GetLength() method returns the length for a given dimension (starting at 0).
for (int i = 0; i < a.GetLength(0); ++i)
{
    for (int j = 0; j < a.GetLength(1); ++j)
    {
        // access an element - arr[i, j]
    }
}

Jagged arrays

A jagged array is an array of arrays. Each row of the jagged array can have different length.

// Declare a jagged array. Each element of the jagged array is initialized to null.
int[][] a = new int[3][];
 
// Create and initialize a jagged array.
int[][] a = new int[3][];
a[0] = new int[] { 1, 2 };
a[1] = new int[] { 3 };
a[2] = new int[] { 4, 5, 6 };
 
// Alternative syntax.
int[][] a =
{
    new int[] { 1, 2 },
    new int[] { 3 },
    new int[] { 4, 5, 6 }
};
 
// Traverse a jagged two-dimensional array using a for loop.
for (int i = 0; i < a.Length; ++i)
{
    for (int j = 0; j < a[i].Length; ++j)
    {
        // access an element - a[i][j]
    }
}

Splitting and Joining

Use String.Join to combine elements of an array into a string. Use the Split method to split a string into elements of an array. More information on splitting and joining strings can be found here.

string[] a = { "a", "b", "c" };
string s = String.Join("|", a); // s = "a|b|c"
 
string s = "x|y|z";
string[] a = s.Split('|'); // a = { "x", "y", "z" }

Copying and Combining

A common approach to combine multiple arrays is to use the List.AddRange method.

int[] a1 = { 1, 2, 3 };
int[] a2 = { 4, 5, 6 };
 
var list = new List<int>();
list.AddRange(a1);
list.AddRange(a2);
 
int[] a = list.ToArray(); // a = { 1, 2, 3, 4, 5, 6 }

Use Array.Copy to copy a subset of an array to another array. This approach has better performance than using the List.AddRange method.

int[] source = { 1, 2, 3, 4, 5 };
 
// specify the length
int[] d1 = new int[5];
Array.Copy(source, d1, 3); // d1 = { 1, 2, 3, 0, 0 }
 
// specify the source index, the destination index, and the length
int[] d2 = new int[5];
Array.Copy(source, 1, d2, 2, 3); // d2 = { 0, 0, 2, 3, 4 }

Use Buffer.BlockCopy to achieve the best performance. Buffer.BlockCopy performs bitwise copy of the bytes.

int[] a1 = { 1, 2, 3 };
int[] a2 = { 4, 5, 6 };
 
int[] a = new int[a1.Length + a2.Length];
 
// Copy a1 to a.
Buffer.BlockCopy(a1, 0, a, 0, a1.Length * sizeof(int));
 
// Copy a2 to a.
int offset = a1.Length * sizeof(int);
Buffer.BlockCopy(a2, 0, a, offset, a2.Length * sizeof(int));
 
// a = { 1, 2, 3, 4, 5, 6 }

Use the Clone method to create a shallow copy of an array.

int[] a1 = { 1, 2, 3 };
int[] a2 = (int[])a1.Clone(); // a2 = { 1, 2, 3 }

Array class

Array types are derived from the abstract base type Array.

Create an array

Use Array.CreateInstance when you don't know the type of elements in advance. You can also create multi-dimensional arrays.

// Create an array containing five integers.
// The array a is of type System.Array
Array a = Array.CreateInstance(typeof(Int32), 5); 
 
// Set and get a value.
a.SetValue(8, 0); // a[0] = 8
int val = (int)a.GetValue(0); // val = 8
 
// Cast the array a from System.Array to int[].
int[] a2 = (int[])a;

Sort an array

Use Array.Sort to sort elements in an array. The Array.Sort method requires the interface IComparable to be implemented by the elements. You can also sort a subset of elements in the array.

int[] a = { 5, 9, 1, 8, 4, 7 };
 
Array.Sort(a); // a = { 1, 4, 5, 7, 8, 9 }

Reverse an array

Use Array.Reverse to reverse elements on an array.

int[] a = { 5, 9, 1, 8, 4, 7 };
 
Array.Reverse(a); // a = { 7, 4, 8, 1, 9, 5 }

Search for an element

Use Array.BinarySearch to find an element in a sorted array using the binary search algorithm. You can also search in a range of elements in the array.

int[] a = { 5, 9, 1, 8, 4, 7 };
 
Array.Sort(a); // the array has to be sorted!
 
int index1 = Array.BinarySearch<int>(a, 4); // index1 == 1 (in the sorted array)
int index2 = Array.BinarySearch<int>(a, 3); // index2 == -2 (a negative value if not found)

Use Array.IndexOf to find the index of the first occurrence of an element.

int[] a = { 5, 9, 1, 8, 4, 7 };
 
int index1 = Array.IndexOf(a, 4); // index1 == 4
int index2 = Array.IndexOf(a, 3); // index2 == -1

Clear an array

Use Array.Clear(arr, i, n) to clear n elements of an array arr starting from index i.

int[] a = { 1, 2, 3, 4, 5 };
 
Array.Clear(a, 0, 3); // a = { 0, 0, 0, 4, 5 }
Array.Clear(a, 1, 4); // a = { 1, 0, 0, 0, 0 }

Resize an array

Use Array.Resize method to change the array's size. Array.Resize allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.

int[] a = { 1, 2, 3 };
Array.Resize<int>(ref a, 6); // a = { 1, 2, 3, 0, 0, 0 }
notes/csharp/arrays.txt · Last modified: 2016/10/26 by admin