Csharp/C Sharp/Collections Data Structure/Array
Содержание
- 1 Array.AsReadOnly Method
- 2 Array.Clone Method
- 3 Array Conversions
- 4 Array.CreateInstance Method
- 5 Array.FindAll Method: This is the syntax of the Predicate delegate:delegate bool Predicate<T>(T obj)
- 6 Array.Resize Method
- 7 Array reverse and sort
- 8 Arrays of Reference Types
- 9 Array.Sort by CultureInfo
- 10 Array.SyncRoot Property: synchronize access to an array.
- 11 A run-time error occurs when Array.Sort is called: XClass does not implement the IComparable interface.
- 12 Assigning array reference variables
- 13 Class array
- 14 Class array init
- 15 Compute the average of a set of values
- 16 Compute the average of a set of values 2
- 17 Copy an array
- 18 Creates an and array and looks for the index of a given value from either end
- 19 Creates and implements an instance of Array
- 20 Demonstrate an array overrun
- 21 Demonstrate a one-dimensional array
- 22 Enumerates an array using an enumerator object
- 23 illustrates an attempt to write to a nonexistent array element
- 24 illustrates how to initialize arrays
- 25 illustrates how to use array properties and methods
- 26 illustrates how to use arrays 2
- 27 illustrates the use of an array of objects
- 28 Jagged Array Demo
- 29 Multi Dimensional Arrays
- 30 Reverse an array
- 31 Reverse an array 2
- 32 Sort an array and search for a value
- 33 Sort and search an array of objects
- 34 Stores a sequence of temperatures in an array
- 35 Sums the values in an array using a foreach loop 1
- 36 System.Array Type:Reverse
- 37 Use object to create a generic array
- 38 Uses the Array.Copy() method to copy an array of ints into an array of doubles 2
- 39 Uses the Array.Copy() method to copy part of an array ints into a secton of an array of doubles
- 40 Use the Length array property
Array.AsReadOnly Method
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class Starter {
public static void Main() {
int[] zArray = { 1, 2, 3, 4 };
zArray[1] = 10;
ReadOnlyCollection<int> roArray = Array.AsReadOnly(zArray);
foreach (int number in roArray) {
Console.WriteLine(number);
}
roArray[1] = 2; // compile error
}
}
Array.Clone Method
using System;
using System.Collections.Generic;
public class Starter {
public static void Main() {
CommissionedEmployee[] salespeople =
{new CommissionedEmployee("Bob"),
new CommissionedEmployee("Ted"),
new CommissionedEmployee("Sally")};
Employee[] employees =
(Employee[])salespeople.Clone();
foreach (Employee person in
employees) {
person.Pay();
}
}
}
public class Employee {
public Employee(string name) {
m_Name = name;
}
public virtual void Pay() {
Console.WriteLine("Paying {0}", m_Name);
}
private string m_Name;
}
public class CommissionedEmployee : Employee {
public CommissionedEmployee(string name) :
base(name) {
}
public override void Pay() {
base.Pay();
Console.WriteLine("Paying commissions");
}
}
Array Conversions
// Arrays\Array Conversions
using System;
public class ArrayConversions
{
public static void PrintArray(object[] arr)
{
foreach (object obj in arr)
Console.WriteLine("Word: {0}", obj);
}
public static void Main()
{
string s = "I will not buy this record, it is scratched.";
char[] separators = {" "};
string[] words = s.Split(separators);
PrintArray(words);
}
}
Array.CreateInstance Method
using System;
using System.Reflection;
public class Starter {
public static void Main(string[] argv) {
Assembly executing = Assembly.GetExecutingAssembly();
Type t = executing.GetType(argv[0]);
Array zArray = Array.CreateInstance(t, argv.Length - 2);
for (int count = 2; count < argv.Length; ++count) {
System.Object obj = Activator.CreateInstance(t, new object[] {argv[count]});
zArray.SetValue(obj, count - 2);
}
foreach (object item in zArray) {
MethodInfo m = t.GetMethod(argv[1]);
m.Invoke(item, null);
}
}
}
public class MyClass {
public MyClass(string info) {
m_Info = "MyClass " + info;
}
public void ShowInfo() {
Console.WriteLine(m_Info);
}
private string m_Info;
}
public class YClass {
public YClass(string info) {
m_Info = "YClass " + info;
}
public void ShowInfo() {
Console.WriteLine(m_Info);
}
private string m_Info;
}
public class XClass {
public XClass(string info) {
m_Info = "XClass " + info;
}
public void ShowInfo() {
Console.WriteLine(m_Info);
}
private string m_Info;
}
Array.FindAll Method: This is the syntax of the Predicate delegate:delegate bool Predicate<T>(T obj)
using System;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
int[] zArray = { 1, 2, 3, 1, 2, 3, 1, 2, 3 };
Predicate<int> match = new Predicate<int>(MethodA<int>);
int[] answers = Array.FindAll(zArray, match);
foreach (int answer in answers) {
Console.WriteLine(answer);
}
}
public static bool MethodA<T>(T number) where T : IComparable {
int result = number.rupareTo(3);
return result == 0;
}
}
Array.Resize Method
using System;
public class Starter {
public static void Main() {
int[] zArray = { 1, 2, 3, 4 };
Array.Resize<int>(ref zArray, 8);
foreach (int number in zArray) {
Console.WriteLine(number);
}
}
}
Array reverse and sort
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
namespace ReverseAndSort
{
public class TesterReverseAndSort
{
public static void DisplayArray(object[] theArray)
{
foreach (object obj in theArray)
{
Console.WriteLine("Value: {0}", obj);
}
Console.WriteLine("\n");
}
public void Run()
{
String[] myArray =
{
"Who", "is", "John", "Galt"
};
Console.WriteLine("Display myArray...");
DisplayArray(myArray);
Console.WriteLine("Reverse and display myArray...");
Array.Reverse(myArray);
DisplayArray(myArray);
String[] myOtherArray =
{
"We", "Hold", "These", "Truths",
"To", "Be", "Self", "Evident",
};
Console.WriteLine("Display myOtherArray...");
DisplayArray(myOtherArray);
Console.WriteLine("Sort and display myOtherArray...");
Array.Sort(myOtherArray);
DisplayArray(myOtherArray);
}
[STAThread]
static void Main()
{
TesterReverseAndSort t = new TesterReverseAndSort();
t.Run();
}
}
}
Arrays of Reference Types
// 16 - Arrays\Arrays of Reference Types
class Employee
{
public static Employee LoadFromDatabase(int employeeID)
{
Employee emp = new Employee();
return(emp);
}
}
public class ArraysofReferenceTypes
{
public static void Main()
{
Employee[] emps = new Employee[3];
emps[0] = Employee.LoadFromDatabase(15);
emps[1] = Employee.LoadFromDatabase(35);
emps[2] = Employee.LoadFromDatabase(255);
}
}
Array.Sort by CultureInfo
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Globalization;
class Program {
static void DisplayNames(IEnumerable e) {
foreach (string s in e)
Console.Write(s + " - ");
}
static void Main(string[] args) {
string[] names = {"Alabama", "Texas", "Washington",
"Virginia", "Wisconsin", "Wyoming",
"Kentucky", "Missouri", "Utah", "Hawaii",
"Kansas", "Lousiana", "Alaska", "Arizona"};
Thread.CurrentThread.CurrentCulture = new CultureInfo("fi-FI");
Array.Sort(names);
DisplayNames(names);
Array.Sort(names, Comparer.DefaultInvariant);
Console.WriteLine("\nsorted with invariant culture...");
DisplayNames(names);
}
}
Array.SyncRoot Property: synchronize access to an array.
using System;
using System.Threading;
public class Starter {
public static void Main() {
Array.Sort(zArray);
Thread t1 = new Thread(new ThreadStart(DisplayForward));
Thread t2 = new Thread(new ThreadStart(DisplayReverse));
t1.Start();
t2.Start();
}
private static int[] zArray = { 1, 5, 4, 2, 4, 2, 9, 10 };
public static void DisplayForward() {
lock (zArray.SyncRoot) {
Console.Write("\nForward: ");
foreach (int number in zArray) {
Console.Write(number);
}
}
}
public static void DisplayReverse() {
lock (zArray.SyncRoot) {
Array.Reverse(zArray);
Console.Write("\nReverse: ");
foreach (int number in zArray) {
Console.Write(number);
}
Array.Reverse(zArray);
}
}
}
A run-time error occurs when Array.Sort is called: XClass does not implement the IComparable interface.
using System;
public class Starter {
public static void Main() {
XClass[] objs ={new XClass(5), new XClass(10),
new XClass(1)};
Array.Sort(objs);
}
}
public class XClass {
public XClass(int data) {
propNumber = data;
}
private int propNumber;
public int Number {
get {
return propNumber;
}
}
}
Assigning array reference variables
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Assigning array reference variables.
using System;
public class AssignARef {
public static void Main() {
int i;
int[] nums1 = new int[10];
int[] nums2 = new int[10];
for(i=0; i < 10; i++) nums1[i] = i;
for(i=0; i < 10; i++) nums2[i] = -i;
Console.Write("Here is nums1: ");
for(i=0; i < 10; i++)
Console.Write(nums1[i] + " ");
Console.WriteLine();
Console.Write("Here is nums2: ");
for(i=0; i < 10; i++)
Console.Write(nums2[i] + " ");
Console.WriteLine();
nums2 = nums1; // now nums2 refers to nums1
Console.Write("Here is nums2 after assignment: ");
for(i=0; i < 10; i++)
Console.Write(nums2[i] + " ");
Console.WriteLine();
// now operate on nums1 array through nums2
nums2[3] = 99;
Console.Write("Here is nums1 after change through nums2: ");
for(i=0; i < 10; i++)
Console.Write(nums1[i] + " ");
Console.WriteLine();
}
}
Class array
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
namespace ArrayDemo
{
// a simple class to store in the array
class Employee
{
private int empID;
// constructor
public Employee(int empID)
{
this.empID = empID;
}
public override string ToString()
{
return empID.ToString();
}
}
public class TesterClassArray
{
public void Run()
{
int[] intArray;
Employee[] empArray;
intArray = new int[5];
empArray = new Employee[3];
// populate the array
for (int i = 0;i<empArray.Length;i++)
{
empArray[i] = new Employee(i+5);
}
Console.WriteLine("The int array...");
for (int i = 0;i<intArray.Length;i++)
{
Console.WriteLine(intArray[i].ToString());
}
Console.WriteLine("\nThe employee array...");
for (int i = 0;i<empArray.Length;i++)
{
Console.WriteLine(empArray[i].ToString());
}
}
[STAThread]
static void Main()
{
TesterClassArray t = new TesterClassArray();
t.Run();
}
}
}
Class array init
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
namespace ArrayDemo
{
// a simple class to store in the array
class Employee
{
private int empID;
// constructor
public Employee(int empID)
{
this.empID = empID;
}
}
public class TesterArrayDemoInit
{
public void Run()
{
int[] intArray;
Employee[] empArray;
intArray = new int[5];
empArray = new Employee[3];
// populate the array
for (int i = 0;i<empArray.Length;i++)
{
empArray[i] = new Employee(i+5);
}
}
[STAThread]
static void Main()
{
TesterArrayDemoInit t = new TesterArrayDemoInit();
t.Run();
}
}
}
Compute the average of a set of values
// Compute the average of a set of values.
using System;
public class Average1 {
public static void Main() {
int[] nums = new int[10];
int avg = 0;
nums[0] = 99;
nums[1] = 10;
nums[2] = 100;
nums[3] = 18;
nums[4] = 78;
nums[5] = 23;
nums[6] = 63;
nums[7] = 9;
nums[8] = 87;
nums[9] = 49;
for(int i=0; i < 10; i++)
avg = avg + nums[i];
avg = avg / 10;
Console.WriteLine("Average: " + avg);
}
}
Compute the average of a set of values 2
// Compute the average of a set of values.
using System;
public class Average {
public static void Main() {
int[] nums = { 99, 10, 100, 18, 78, 23, 63, 9, 87, 49 };
int avg = 0;;
for(int i=0; i < 10; i++) {
avg = avg + nums[i];
}
avg = avg / 10;
Console.WriteLine("Average: " + avg);
}
}
Copy an array
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Copy an array.
using System;
public class CopyDemo {
public static void Main() {
int[] source = { 1, 2, 3, 4, 5 };
int[] target = { 11, 12, 13, 14, 15 };
int[] source2 = { -1, -2, -3, -4, -5 };
// Display source.
Console.Write("source: ");
foreach(int i in source)
Console.Write(i + " ");
Console.WriteLine();
// Display original target.
Console.Write("Original contents of target: ");
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();
// Copy the entire array.
Array.Copy(source, target, source.Length);
// Display copy.
Console.Write("target after copy: ");
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();
// Copy into middle of target.
Array.Copy(source2, 2, target, 3, 2);
// Display copy.
Console.Write("target after copy: ");
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();
}
}
Creates an and array and looks for the index of a given value from either end
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// Index.cs -- Creates an and array and looks for the index of a given
// value from either end.
//
// Compile this program with the following command line:
// C:>csc Index.cs
//
namespace nsArray
{
using System;
public class Index
{
static public void Main ()
{
int [] Arr = new int [12]
{29, 82, 42, 46, 54, 65, 50, 42, 5, 94, 19, 34};
Console.WriteLine ("The first occurrence of 42 is at index "
+ Array.IndexOf(Arr, 42));
Console.WriteLine ("The last occurrence of 42 is at index "
+ Array.LastIndexOf(Arr, 42));
int x = 0;
while ((x = Array.IndexOf (Arr, 42, x)) >= 0)
{
Console.WriteLine ("42 found at index " + x);
++x;
}
x = Arr.Length - 1;
while ((x = Array.LastIndexOf (Arr, 42, x)) >= 0)
{
Console.WriteLine ("42 found at index " + x);
--x;
}
}
}
}
Creates and implements an instance of Array
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// CreatArr.cs -- Creates and implements an instance of Array
//
// Compile this program with the following command line:
// C:>csc CreatArr.cs
//
namespace nsArray
{
using System;
public class CreatArr
{
static public void Main ()
{
DateTime now = DateTime.Now;
Random rand = new Random ((int) now.Millisecond);
// Create an instance of the Array class.
Array Arr = Array.CreateInstance (typeof(Int32), 10);
// Initialize the elements using the SetValue() member method
// Use the GetLowerBound() and GetUpperBound() methods for safe access.
for (int x = Arr.GetLowerBound(0); x < Arr.GetUpperBound(0) + 1; ++x)
{
Arr.SetValue (rand.Next () % 100, x);
}
int Total = 0;
Console.Write ("Array values are ");
// Use the foreach loop on the Array instance
foreach (int val in Arr)
{
Total += val;
Console.Write (val + ", ");
}
Console.WriteLine ("and the average is {0,0:F1}",
(double) Total / (double) Arr.Length);
}
}
}
Demonstrate an array overrun
// Demonstrate an array overrun.
using System;
public class ArrayErr {
public static void Main() {
int[] sample = new int[10];
int i;
// generate an array overrun
for(i = 0; i < 100; i = i+1) {
sample[i] = i;
}
}
}
Demonstrate a one-dimensional array
// Demonstrate a one-dimensional array.
using System;
public class ArrayDemo {
public static void Main() {
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1) {
sample[i] = i;
}
for(i = 0; i < 10; i = i+1) {
Console.WriteLine("sample[" + i + "]: " + sample[i]);
}
}
}
Enumerates an array using an enumerator object
using System;
using System.Collections;
public class Starter {
public static void Main() {
int[] numbers = { 1, 2, 3, 4, 5 };
IEnumerator e = numbers.GetEnumerator();
while (e.MoveNext()) {
Console.WriteLine(e.Current);
}
}
}
illustrates an attempt to write to a nonexistent array element
/*
illustrates an attempt to write to a nonexistent array element
*/
using System;
public class Example10_2 {
public static void Main() {
try {
int[] intArray = new int[5];
for (int counter = 0; counter <= intArray.Length; counter++)
{
intArray[counter] = counter;
Console.WriteLine("intArray[" + counter + "] = " + intArray[counter]);
}
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("IndexOutOfRangeException occurred");
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("Stack trace = " + e.StackTrace);
}
}
}
illustrates how to initialize arrays
/*
Example10_3.cs illustrates how to initialize arrays
*/
using System;
public class Example10_3 {
public static void Main() {
// int arrays
int[] intArray = new int[5] {10, 20, 30, 40, 50};
for (int counter = 0; counter < intArray.Length; counter++)
{
Console.WriteLine("intArray[" + counter + "] = " +
intArray[counter]);
}
// char arrays
char[] charArray = new char[] {"h", "e", "l", "l", "o"};
for (int counter = 0; counter < charArray.Length; counter++)
{
Console.WriteLine("charArray[" + counter + "] = " +
charArray[counter]);
}
// string arrays
string[] stringArray = {"Hello", "World"};
foreach (string myString in stringArray)
{
Console.WriteLine("myString = " + myString);
}
}
}
illustrates how to use array properties and methods
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example10_5.cs illustrates how to use array properties
and methods
*/
using System;
public class Example10_5
{
public static void Main()
{
// use the Sort() method to sort the elements in an int array
int[] intArray = {5, 2, 3, 1, 6, 9, 7, 14, 25};
Array.Sort(intArray); // sort the elements
Console.WriteLine("Sorted intArray:");
for (int counter = 0; counter < intArray.Length; counter++)
{
Console.WriteLine("intArray[" + counter + "] = " +
intArray[counter]);
}
// use the Sort() method to sort the elements in a string array
string[] stringArray = {"this", "is", "a", "test", "abc123", "abc345"};
Array.Sort(stringArray); // sort the elements
Console.WriteLine("Sorted stringArray:");
for (int counter = 0; counter < stringArray.Length; counter++)
{
Console.WriteLine("stringArray[" + counter + "] = " +
stringArray[counter]);
}
// use the Sort() method to sort the elements in a char array
char[] charArray = {"w", "e", "l", "c", "o", "m", "e"};
Array.Sort(charArray); // sort the elements
Console.WriteLine("Sorted charArray:");
for (int counter = 0; counter < charArray.Length; counter++)
{
Console.WriteLine("charArray[" + counter + "] = " +
charArray[counter]);
}
// use the BinarySearch() method to search intArray for the number 5
int index = Array.BinarySearch(intArray, 5);
Console.WriteLine("Array.BinarySearch(intArray, 5) = " + index);
// use the BinarySearch() method to search intArray for the number 4
// (this number doesn"t exist in intArray, and therefore BinarySearch()
// returns a negative value)
index = Array.BinarySearch(intArray, 4);
Console.WriteLine("Array.BinarySearch(intArray, 4) = " + index);
// use the BinarySearch() method to search stringArray for "abc345"
index = Array.BinarySearch(stringArray, "abc345");
Console.WriteLine("Array.BinarySearch(stringArray, \"abc345\") = " + index);
// use the BinarySearch() method to search charArray for "o"
index = Array.BinarySearch(charArray, "o");
Console.WriteLine("Array.BinarySearch(charArray, "o") = " + index);
// use the Reverse() method to reverse the elements in intArray
Array.Reverse(intArray);
Console.WriteLine("Reversed intArray:");
for (int counter = 0; counter < intArray.Length; counter++)
{
Console.WriteLine("intArray[" + counter + "] = " +
intArray[counter]);
}
// use the Reverse() method to reverse the elements in stringArray
Array.Reverse(stringArray);
Console.WriteLine("Reversed stringArray:");
for (int counter = 0; counter < stringArray.Length; counter++)
{
Console.WriteLine("stringArray[" + counter + "] = " +
stringArray[counter]);
}
// use the Reverse() method to reverse the elements in charArray
Array.Reverse(charArray);
Console.WriteLine("Reversed charArray:");
for (int counter = 0; counter < charArray.Length; counter++)
{
Console.WriteLine("charArray[" + counter + "] = " +
charArray[counter]);
}
// create another array of int values named intArray2
int[] intArray2 = {1, 2, 1, 3};
Console.WriteLine("intArray2:");
for (int counter = 0; counter < intArray2.Length; counter++)
{
Console.WriteLine("intArray2[" + counter + "] = " +
intArray2[counter]);
}
// use the IndexOf() and LastIndexOf() methods to find the value 1
// in intArray2
index = Array.IndexOf(intArray2, 1);
Console.WriteLine("Array.IndexOf(intArray2, 1) = " + index);
index = Array.LastIndexOf(intArray2, 1);
Console.WriteLine("Array.LastIndexOf(intArray2, 1) = " + index);
// create another array of strings named stringArray2
string[] stringArray2 = {"Hello", "to", "everyone", "Hello", "all"};
Console.WriteLine("stringArray2:");
for (int counter = 0; counter < stringArray2.Length; counter++)
{
Console.WriteLine("stringArray2[" + counter + "] = " +
stringArray2[counter]);
}
// use the IndexOf() and LastIndexOf() methods to find the string "Hello"
// in intArray2
index = Array.IndexOf(stringArray2, "Hello");
Console.WriteLine("Array.IndexOf(stringArray2, \"Hello\") = " + index);
index = Array.LastIndexOf(stringArray2, "Hello");
Console.WriteLine("Array.LastIndexOf(stringArray2, \"Hello\") = " + index);
}
}
illustrates how to use arrays 2
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example10_1.cs illustrates how to use arrays
*/
using System;
public class Example10_1
{
public static void Main()
{
// int arrays
int[] intArray = new int[10];
int arrayLength = intArray.Length;
Console.WriteLine("arrayLength = " + arrayLength);
for (int counter = 0; counter < arrayLength; counter++)
{
intArray[counter] = counter;
Console.WriteLine("intArray[" + counter + "] = " +
intArray[counter]);
}
// char arrays
char[] charArray = new char[5];
Console.WriteLine("charArray[0] = " + charArray[0]);
charArray[0] = "h";
charArray[1] = "e";
charArray[2] = "l";
charArray[3] = "l";
charArray[4] = "o";
for (int counter = 0; counter < charArray.Length; counter++)
{
Console.WriteLine("charArray[" + counter + "] = " +
charArray[counter]);
}
// string arrays
string[] stringArray = new string[2];
Console.WriteLine("stringArray[0] = " + stringArray[0]);
stringArray[0] = "Hello";
stringArray[1] = "World";
foreach (string myString in stringArray)
{
Console.WriteLine("myString = " + myString);
}
}
}
illustrates the use of an array of objects
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example10_10.cs illustrates the use of
an array of objects
*/
using System;
// declare the Star class
class Star
{
// declare two fields
public string name;
public int brightness;
// declare a constructor
public Star(
string name,
int brightness
)
{
this.name = name;
this.brightness = brightness;
}
}
public class Example10_10
{
public static void Main()
{
// create the galaxy array of Star objects
Star[,,] galaxy = new Star[10, 5, 3];
// create two Star objects in the galaxy array
galaxy[1, 3, 2] = new Star("Sun", 3);
galaxy[4, 1, 2] = new Star("Alpha Centuri", 9);
// display the Rank and Length properties of the galaxy array
Console.WriteLine("galaxy.Rank (number of dimensions) = " + galaxy.Rank);
Console.WriteLine("galaxy.Length (number of elements) = " + galaxy.Length);
// display the galaxy array elements
for (int x = 0; x < galaxy.GetLength(0); x++)
{
for (int y = 0; y < galaxy.GetLength(1); y++)
{
for (int z = 0; z < galaxy.GetLength(2); z++)
{
if (galaxy[x, y, z] != null)
{
Console.WriteLine("galaxy[" + x + ", " + y + ", " + z +"].name = " +
galaxy[x, y, z].name);
Console.WriteLine("galaxy[" + x + ", " + y + ", " + z +"].brightness = " +
galaxy[x, y, z].brightness);
}
}
}
}
}
}
Jagged Array Demo
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
namespace JaggedArray
{
public class TesterJaggedArray
{
[STAThread]
static void Main()
{
const int rows = 4;
const int rowZero = 5; // num elements
const int rowOne = 2;
const int rowTwo = 3;
const int rowThree = 5;
// declare the jagged array as 4 rows high
int[][] jaggedArray = new int[rows][];
// declare the rows of various lengths
jaggedArray[0] = new int[rowZero];
jaggedArray[1] = new int[rowOne];
jaggedArray[2] = new int[rowTwo];
jaggedArray[3] = new int[rowThree];
// Fill some (but not all) elements of the rows
jaggedArray[0][3] = 15;
jaggedArray[1][1] = 12;
jaggedArray[2][1] = 9;
jaggedArray[2][2] = 99;
jaggedArray[3][0] = 10;
jaggedArray[3][1] = 11;
jaggedArray[3][2] = 12;
jaggedArray[3][3] = 13;
jaggedArray[3][4] = 14;
for (int i = 0;i < rowZero; i++)
{
Console.WriteLine("jaggedArray[0][{0}] = {1}",
i,jaggedArray[0][i]);
}
for (int i = 0;i < rowOne; i++)
{
Console.WriteLine("jaggedArray[1][{0}] = {1}",
i,jaggedArray[1][i]);
}
for (int i = 0;i < rowTwo; i++)
{
Console.WriteLine("jaggedArray[2][{0}] = {1}",
i,jaggedArray[2][i]);
}
for (int i = 0;i < rowThree; i++)
{
Console.WriteLine("jaggedArray[3][{0}] = {1}",
i,jaggedArray[3][i]);
}
}
}
}
Multi Dimensional Arrays
/*
Learning C#
by Jesse Liberty
Publisher: O"Reilly
ISBN: 0596003765
*/
using System;
namespace MultiDimensionalArrays
{
public class TesterMultiDimensionalArrays
{
[STAThread]
static void Main()
{
const int rows = 4;
const int columns = 3;
// declare a 4x3 integer array
int[,] rectangularArray = new int[rows, columns];
// populate the array
for (int i = 0;i < rows;i++)
{
for (int j = 0;j<columns;j++)
{
rectangularArray[i,j] = i+j;
}
}
// report the contents of the array
for (int i = 0;i < rows;i++)
{
for (int j = 0;j<columns;j++)
{
Console.WriteLine("rectangularArray[{0},{1}] = {2}",
i,j,rectangularArray[i,j]);
}
}
}
}
}
Reverse an array
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Reverse an array.
using System;
public class ReverseDemo {
public static void Main() {
int[] nums = { 1, 2, 3, 4, 5 };
// Display original order.
Console.Write("Original order: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
// Reverse the entire array.
Array.Reverse(nums);
// Display reversed order.
Console.Write("Reversed order: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
// Reverse a range.
Array.Reverse(nums, 1, 3);
// Display reversed order.
Console.Write("Range reversed: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
}
}
Reverse an array 2
// Reverse an array.
using System;
public class RevCopy {
public static void Main() {
int i,j;
int[] nums1 = new int[10];
int[] nums2 = new int[10];
for(i=0; i < nums1.Length; i++) nums1[i] = i;
Console.Write("Original contents: ");
for(i=0; i < nums2.Length; i++)
Console.Write(nums1[i] + " ");
Console.WriteLine();
// reverse copy nums1 to nums2
if(nums2.Length >= nums1.Length){
for(i=0, j=nums1.Length-1; i < nums1.Length; i++, j--) {
nums2[j] = nums1[i];
}
}
Console.Write("Reversed contents: ");
for(i=0; i < nums2.Length; i++)
Console.Write(nums2[i] + " ");
Console.WriteLine();
}
}
Sort an array and search for a value
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Sort an array and search for a value.
using System;
public class SortDemo {
public static void Main() {
int[] nums = { 5, 4, 6, 3, 14, 9, 8, 17, 1, 24, -1, 0 };
// Display original order.
Console.Write("Original order: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
// Sort the array.
Array.Sort(nums);
// Display sorted order.
Console.Write("Sorted order: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
// Search for 14.
int idx = Array.BinarySearch(nums, 14);
Console.WriteLine("Index of 14 is " + idx);
}
}
Sort and search an array of objects
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Sort and search an array of objects.
using System;
class MyClass : IComparable {
public int i;
public MyClass(int x) { i = x; }
// Implement IComparable.
public int CompareTo(object v) {
return i - ((MyClass)v).i;
}
}
public class SortDemo1 {
public static void Main() {
MyClass[] nums = new MyClass[5];
nums[0] = new MyClass(5);
nums[1] = new MyClass(2);
nums[2] = new MyClass(3);
nums[3] = new MyClass(4);
nums[4] = new MyClass(1);
// Display original order.
Console.Write("Original order: ");
foreach(MyClass o in nums)
Console.Write(o.i + " ");
Console.WriteLine();
// Sort the array.
Array.Sort(nums);
// Display sorted order.
Console.Write("Sorted order: ");
foreach(MyClass o in nums)
Console.Write(o.i + " ");
Console.WriteLine();
// Search for MyClass(2).
MyClass x = new MyClass(2);
int idx = Array.BinarySearch(nums, x);
Console.WriteLine("Index of MyClass(2) is " + idx);
}
}
Stores a sequence of temperatures in an array
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// GetTemps.cs -- Stores a sequence of temperatures in an array
//
// Compile this program with the following command line:
// C:>csc GetTemps.cs
//
namespace nsTemperatures
{
using System;
public class GetTemps
{
static public void Main ()
{
int [] Temps = new int [24]
{48, 47, 45, 45, 44, 45, 48, 54,
59, 64, 70, 75, 86, 92, 98, 101,
99, 97, 96, 91, 82, 70, 63, 55}
;
for (int x = 0; x < 24; ++x)
{
while (true)
{
Console.Write ("Enter the temperature for " +
(x == 0 ? "Midnight"
: (x == 12 ? "Noon"
: ((x < 12 ? x.ToString() + " a."
: ((x - 12).ToString() + " p."))
+ "m."))) + ": "
);
try
{
Temps[x] = Convert.ToInt32 (Console.ReadLine ());
break;
}
catch
{
Console.WriteLine ("\r\nPlease enter a number value.");
}
}
}
Console.WriteLine ("The daily temperature report:");
for (int x = 0; x < 24; x += 4)
{
Console.WriteLine ("{0,4:D4} : {1,3:D}\t{2,4:D4}: {3,3:D}\t" +
"{4,4:D4}: {5,3:D}\t{6,4:D4}: {7,3:D}",
x * 100, Temps[x],
(x + 1) * 100, Temps[x + 1],
(x + 2) * 100, Temps[x + 2],
(x + 3) * 100, Temps[x + 3]);
}
}
}
}
Sums the values in an array using a foreach loop 1
// Sums the values in an array using a foreach loop
using System;
public class InitArr
{
static public void Main ()
{
DateTime now = DateTime.Now;
Random rand = new Random ((int) now.Millisecond);
int [] Arr = new int []
{rand.Next () % 100, rand.Next () % 100,
rand.Next () % 100, rand.Next () % 100,
rand.Next () % 100, rand.Next () % 100,
rand.Next () % 100, rand.Next () % 100,
rand.Next () % 100, rand.Next () % 100
};
int Total = 0;
Console.Write ("Array values are ");
foreach (int val in Arr)
{
Total += val;
Console.Write (val + ", ");
}
Console.WriteLine ("and the average is {0,0:F1}",
(double) Total / (double) Arr.Length);
}
}
System.Array Type:Reverse
using System;
public class SystemArrayTypeReverse
{
public static void Main()
{
int[] arr = {5, 6, 7};
Array.Reverse(arr);
foreach (int value in arr)
{
Console.WriteLine("Value: {0}", value);
}
}
}
Use object to create a generic array
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use object to create a generic array.
using System;
public class GenericDemo {
public static void Main() {
object[] ga = new object[10];
// store ints
for(int i=0; i < 3; i++)
ga[i] = i;
// store doubles
for(int i=3; i < 6; i++)
ga[i] = (double) i / 2;
// store two strings, a bool, and a char
ga[6] = "Generic Array";
ga[7] = true;
ga[8] = "X";
ga[9] = "end";
for(int i = 0; i < ga.Length; i++)
Console.WriteLine("ga[" + i + "]: " + ga[i] + " ");
}
}
Uses the Array.Copy() method to copy an array of ints into an array of doubles 2
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// Int2Dbl.cs -- Uses the Array.Copy() method to copy an array of ints
// into an array of doubles.
//
// Compile this program with the following command line:
// C:>csc Int2Dbl.cs
//
namespace nsArray
{
using System;
public class Int2Dbl
{
static public void Main ()
{
DateTime now = DateTime.Now;
Random rand = new Random ((int) now.Millisecond);
int [] iArr = new int [10]
{
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101
};
double [] dArr = new double [8];
Array.Copy (iArr, dArr, dArr.Length);
Console.Write ("The dArr contains:\r\n ");
foreach (double d in dArr)
{
Console.Write ("{0,4:F1} ", d);
}
Console.Write ("\r\n\r\nThe iArr contains:\r\n ");
foreach (int x in iArr)
{
Console.Write (x + " ");
}
Console.WriteLine ();
}
}
}
Uses the Array.Copy() method to copy part of an array ints into a secton of an array of doubles
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// CopyPart.cs -- Uses the Array.Copy() method to copy part of an array
// ints into a secton of an array of doubles.
//
// Compile this program with the following command line:
// C:>csc CopyPart.cs
//
namespace nsArray
{
using System;
public class CopyPart
{
static public void Main ()
{
DateTime now = DateTime.Now;
Random rand = new Random ((int) now.Millisecond);
int [] iArr = new int [12]
{
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101,
rand.Next() % 101, rand.Next() % 101
};
double [] dArr = new double [14];
Array.Copy (iArr, 2, dArr, 4, 8);
Console.Write ("The dArr contains:\r\n ");
for (int x = 0; x < dArr.Length; ++x)
{
Console.Write ("{0,4:F1} ", dArr[x]);
if (x == 6)
Console.Write("\r\n ");
}
Console.Write ("\r\n\r\nThe iArr contains:\r\n ");
foreach (int x in iArr)
{
Console.Write (x + " ");
}
Console.WriteLine ();
}
}
}
Use the Length array property
// Use the Length array property.
using System;
public class LengthDemo {
public static void Main() {
int[] nums = new int[10];
Console.WriteLine("Length of nums is " + nums.Length);
for(int i=0; i < nums.Length; i++)
nums[i] = i * i;
Console.Write("Here is nums: ");
for(int i=0; i < nums.Length; i++)
Console.Write(nums[i] + " ");
Console.WriteLine();
}
}