CSharp examples for Language Basics:Array
Array class static methods for common array manipulations.
using System;/* www . j a v a 2 s .co m*/ using static System.Array; using System.Collections; class UsingArray { private static int[] intValues = { 1, 2, 3, 4, 5, 6 }; private static double[] doubleValues = { 8.4, 9.4, 0.4, 7.4, 1.4 }; private static int[] intValuesCopy; static void Main() { intValuesCopy = new int[intValues.Length]; // defaults to zeroes PrintArrays(); // output initial array contents // sort doubleValues Sort(doubleValues); // unqualified call to Array static method Sort // copy intValues into intValuesCopy Array.Copy(intValues, intValuesCopy, intValues.Length); Console.WriteLine("\nArray values after Sort and Copy:\n"); PrintArrays(); // output array contents Console.WriteLine(); // search for 5 in intValues int result = Array.BinarySearch(intValues, 5); Console.WriteLine(result >= 0 ? $"5 found at element {result} in intValues" : "5 not found in intValues"); // search for 8763 in intValues result = Array.BinarySearch(intValues, 8763); Console.WriteLine(result >= 0 ? $"8763 found at element {result} in intValues" : "8763 not found in intValues"); } private static void PrintArrays() { Console.Write("doubleValues: "); IEnumerator enumerator = doubleValues.GetEnumerator(); while (enumerator.MoveNext()) { Console.Write($"{enumerator.Current} "); } Console.Write("\nintValues: "); enumerator = intValues.GetEnumerator(); while (enumerator.MoveNext()) { Console.Write($"{enumerator.Current} "); } Console.Write("\nintValuesCopy: "); // iterate through the second int array with a foreach statement foreach (var element in intValuesCopy) { Console.Write($"{element} "); } Console.WriteLine(); } }