2. Arrays and Tuples Prepared By : Abed ElAzeem Bukhari What’s in This Chapter? . Simple arrays . Multidimensional arrays . Jagged arrays . The Array class . Arrays as parameters . Enumerations . Tuples . Structural comparison
3.
4. accessing array elements int[] myArray = new int[] {4, 7, 11, 2}; int v1 = myArray[0]; // read first element int v2 = myArray[1]; // read second element myArray[3] = 44; // change fourth element //you can use the Length property that is used in this //for for (int i = 0; i < myArray.Length; i++) { Console.WriteLine(myArray[i]); } statement: /you can also use the foreach statement: foreach (var val in myArray) { Console.WriteLine(val); }
5. using reference Types public class Person { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return String.Format("{0} {1}", FirstName, LastName); } } Person[] myPersons = new Person[2];
6. using reference Types cont. myPersons[0] = new Person { FirstName=“Ahmad", LastName=“Shawahne" }; myPersons[1] = new Person { FirstName=“Abed", LastName=“Bukhari" }; Person[] myPersons2 = { new Person { FirstName=“Hamza", LastName=“Mohammad"}, new Person { FirstName=“Khaled", LastName=“Ahmad"} };
8. multidimensional arrays cont. By using two commas inside the brackets, you can declare a three - dimensional array: int [,,] threedim = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } }, { { 9, 10 }, { 11, 12 } } }; Console.WriteLine(threedim[0, 1, 1]);
9. jagged arrays int [][] jagged = new int[3][]; jagged[0] = new int[2] { 1, 2 }; jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 }; jagged[2] = new int[3] { 9, 10, 11 };
10. jagged arrays cont. for (int row = 0; row < jagged.Length; row++) { for (int element = 0; element < jagged[row].Length; element++) { Console.WriteLine(" row: {0}, element: {1}, value: {2} ", row , element , jagged[row][element] ); } } The outcome of the iteration displays the rows and every element within the rows: row: 0, element: 0, value: 1 row: 0, element: 1, value: 2 row: 1, element: 0, value: 3 row: 1, element: 1, value: 4 row: 1, element: 2, value: 5 row: 1, element: 3, value: 6 row: 1, element: 4, value: 7 row: 1, element: 5, value: 8 row: 2, element: 1, value: 9 row: 2, element: 2, value: 10 row: 2, element: 3, value: 11
11. Array Class Creating arrays: Array intArray1 = Array.CreateInstance(typeof(int), 5); for (int i = 0; i < 5; i++) { intArray1.SetValue(33, i); } for (int i = 0; i < 5; i++) { Console.WriteLine(intArray1.GetValue(i)); } // you can use casting to assing the array to another array int[] intArray2 = (int[])intArray1; Sample1/Program.cs
12. Copying arrays int[] intArray1 = {1, 2}; int[] intArray2 = (int[])intArray1.Clone(); Sample1/Program.cs Instead of using the Clone() method, you can use the Array.Copy() method, which creates a shallow copy as well. But there’s one important difference with Clone() and Copy() : Clone() creates a new array; With Copy() you have to pass an existing array with the same rank and enough elements. If you need a deep copy of an array containing reference types, you have to iterate the array and create new objects.
16. Array Covariance For example, you can declare a parameter of type object[] as shown and pass a Person[] to it: static void DisplayArray( object [] data) { //... } Array covariance is only possible with reference types, not with value types.
17. Arraysegment < T > static int SumOfSegments( ArraySegment<int>[] segments) { int sum = 0; foreach (var segment in segments) { for (int i = segment .Offset ; i < segment .Offset + segment .Count ; i++) { sum += segment.Array[i]; } } return sum; } ArraySegmentSample/Program.cs
18. Arraysegment < T > cont int[] ar1 = { 1, 4, 5, 11, 13, 18 }; int[] ar2 = { 3, 4, 5, 18, 21, 27, 33 }; var segments = new ArraySegment <int>[2] { new ArraySegment<int> (ar1, 0, 3), new ArraySegment<int> (ar2, 3, 3) }; var sum = SumOfSegments(segments);
20. NET 4.0 : System.Tuple A tuple is data structure which can contain different types of data coupled. This is what makes it different from a List or other generic types.
22. NET 4.0 : System.Tuple cont var tupleWithMoreThan8Elements = System.Tuple.Create("is", 2.3, 4.0 f , new List { 'e', 't', 'h' }, “najah", new Stack(4), "best", squaresList); // we'll sort the list of chars in descending order tupleWithMoreThan8Elements.Item4 .Sort(); tupleWithMoreThan8Elements.Item4 .Reverse(); Console.WriteLine("{ 0 } { 1 } { 2 } { 3 }", tupleWithMoreThan8Elements.Item5 , tupleWithMoreThan8Elements.Item1 , string.Concat(tupleWithMoreThan8Elements.Item4) , tupleWithMoreThan8Elements.Item7 ); Console.WriteLine("Rest: {0}", tupleWithMoreThan8Elements.Rest ); Console.WriteLine("Rest's 2nd element: {0}", tupleWithMoreThan8Elements. Rest.Item1.Item2 ); Console.WriteLine("Rest's 5th element: {0}",tupleWithMoreThan8Elements .Rest.Item1.Item5 );
23. Structural Comparison Both arrays and tuples implement the interfaces IStructuralEquatable and IStructuralComparable . StructuralComparison/Person.cs StructuralComparison/Program.cs
// Sample1/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Arrays { class Program { static void Main() { SimpleArrays(); TwoDim(); ThreeDim(); Jagged(); ArrayClass(); CopyArrays(); } static void CopyArrays() { Person[] beatles = { new Person { FirstName=&quot;John&quot;, LastName=&quot;Lennon&quot; }, new Person { FirstName=&quot;Paul&quot;, LastName=&quot;McCartney&quot; } }; Person[] beatlesClone = (Person[])beatles.Clone(); } static void ArrayClass() { Array intArray1 = Array.CreateInstance(typeof(int), 5); for (int i = 0; i < 5; i++) { intArray1.SetValue(33, i); } for (int i = 0; i < 5; i++) { Console.WriteLine(intArray1.GetValue(i)); } int[] lengths = { 2, 3 }; int[] lowerBounds = { 1, 10 }; Array racers = Array.CreateInstance(typeof(Person), lengths, lowerBounds); racers.SetValue(new Person { FirstName = &quot;Alain&quot;, LastName = &quot;Prost&quot; }, 1, 10); racers.SetValue(new Person { FirstName = &quot;Emerson&quot;, LastName = &quot;Fittipaldi&quot; }, 1, 11); racers.SetValue(new Person { FirstName = &quot;Ayrton&quot;, LastName = &quot;Senna&quot; }, 1, 12); racers.SetValue(new Person { FirstName = &quot;Ralf&quot;, LastName = &quot;Schumacher&quot; }, 2, 10); racers.SetValue(new Person { FirstName = &quot;Fernando&quot;, LastName = &quot;Alonso&quot; }, 2, 11); racers.SetValue(new Person { FirstName = &quot;Jenson&quot;, LastName = &quot;Button&quot; }, 2, 12); Person[,] racers2 = (Person[,])racers; Person first = racers2[1, 10]; Person last = racers2[2, 12]; } static void Jagged() { int[][] jagged = new int[3][]; jagged[0] = new int[2] { 1, 2 }; jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 }; jagged[2] = new int[3] { 9, 10, 11 }; for (int row = 0; row < jagged.Length; row++) { for (int element = 0; element < jagged[row].Length; element++) { Console.WriteLine( &quot;row: {0}, element: {1}, value: {2}&quot;, row, element, jagged[row][element]); } } } static void ThreeDim() { int[, ,] threedim = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } }, { { 9, 10 }, { 11, 12 } } }; Console.WriteLine(threedim[0, 1, 1]); } static void TwoDim() { int[,] twodim = new int[3, 3]; twodim[0, 0] = 1; twodim[0, 1] = 2; twodim[0, 2] = 3; twodim[1, 0] = 4; twodim[1, 1] = 5; twodim[1, 2] = 6; twodim[2, 0] = 7; twodim[2, 1] = 8; twodim[2, 2] = 9; } static void SimpleArrays() { Person[] myPersons = new Person[2]; myPersons[0] = new Person { FirstName = &quot;Ayrton&quot;, LastName = &quot;Senna&quot; }; myPersons[1] = new Person { FirstName = &quot;Michael&quot;, LastName = &quot;Schumacher&quot; }; Person[] myPersons2 = { new Person { FirstName=&quot;Ayrton&quot;, LastName=&quot;Senna&quot;}, new Person { FirstName=&quot;Michael&quot;, LastName=&quot;Schumacher&quot;} }; } } }
// Sample1/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Arrays { class Program { static void Main() { SimpleArrays(); TwoDim(); ThreeDim(); Jagged(); ArrayClass(); CopyArrays(); } static void CopyArrays() { Person[] beatles = { new Person { FirstName=&quot;John&quot;, LastName=&quot;Lennon&quot; }, new Person { FirstName=&quot;Paul&quot;, LastName=&quot;McCartney&quot; } }; Person[] beatlesClone = (Person[])beatles.Clone(); } static void ArrayClass() { Array intArray1 = Array.CreateInstance(typeof(int), 5); for (int i = 0; i < 5; i++) { intArray1.SetValue(33, i); } for (int i = 0; i < 5; i++) { Console.WriteLine(intArray1.GetValue(i)); } int[] lengths = { 2, 3 }; int[] lowerBounds = { 1, 10 }; Array racers = Array.CreateInstance(typeof(Person), lengths, lowerBounds); racers.SetValue(new Person { FirstName = &quot;Alain&quot;, LastName = &quot;Prost&quot; }, 1, 10); racers.SetValue(new Person { FirstName = &quot;Emerson&quot;, LastName = &quot;Fittipaldi&quot; }, 1, 11); racers.SetValue(new Person { FirstName = &quot;Ayrton&quot;, LastName = &quot;Senna&quot; }, 1, 12); racers.SetValue(new Person { FirstName = &quot;Ralf&quot;, LastName = &quot;Schumacher&quot; }, 2, 10); racers.SetValue(new Person { FirstName = &quot;Fernando&quot;, LastName = &quot;Alonso&quot; }, 2, 11); racers.SetValue(new Person { FirstName = &quot;Jenson&quot;, LastName = &quot;Button&quot; }, 2, 12); Person[,] racers2 = (Person[,])racers; Person first = racers2[1, 10]; Person last = racers2[2, 12]; } static void Jagged() { int[][] jagged = new int[3][]; jagged[0] = new int[2] { 1, 2 }; jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 }; jagged[2] = new int[3] { 9, 10, 11 }; for (int row = 0; row < jagged.Length; row++) { for (int element = 0; element < jagged[row].Length; element++) { Console.WriteLine( &quot;row: {0}, element: {1}, value: {2}&quot;, row, element, jagged[row][element]); } } } static void ThreeDim() { int[, ,] threedim = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } }, { { 9, 10 }, { 11, 12 } } }; Console.WriteLine(threedim[0, 1, 1]); } static void TwoDim() { int[,] twodim = new int[3, 3]; twodim[0, 0] = 1; twodim[0, 1] = 2; twodim[0, 2] = 3; twodim[1, 0] = 4; twodim[1, 1] = 5; twodim[1, 2] = 6; twodim[2, 0] = 7; twodim[2, 1] = 8; twodim[2, 2] = 9; } static void SimpleArrays() { Person[] myPersons = new Person[2]; myPersons[0] = new Person { FirstName = &quot;Ayrton&quot;, LastName = &quot;Senna&quot; }; myPersons[1] = new Person { FirstName = &quot;Michael&quot;, LastName = &quot;Schumacher&quot; }; Person[] myPersons2 = { new Person { FirstName=&quot;Ayrton&quot;, LastName=&quot;Senna&quot;}, new Person { FirstName=&quot;Michael&quot;, LastName=&quot;Schumacher&quot;} }; } } } //sample1/person.cs using System; namespace Najah.ILoveCsharp.Arrays { public class Person { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return String.Format(&quot;{0} {1}&quot;, FirstName, LastName); } } }
//SortingSample/Person.cs using System; namespace Najah.ILoveCsharp.Arrays { public class Person : IComparable<Person> { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return String.Format(&quot;{0} {1}&quot;, FirstName, LastName); } public int CompareTo(Person other) { if (other == null) throw new ArgumentNullException(&quot;other&quot;); int result = this.LastName.CompareTo(other.LastName); if (result == 0) { result = this.FirstName.CompareTo(other.FirstName); } return result; } } } //SortingSample/Program.cs using System; namespace Najah.ILoveCsharp.Arrays { class Program { static void Main() { SortNames(); Person[] persons = GetPersons(); SortPersons(persons); Console.WriteLine(); SortUsingPersonComparer(persons); Covariance(persons); } static void Covariance(object[] objects) { } static void SortUsingPersonComparer(Person[] persons) { Array.Sort(persons, new PersonComparer(PersonCompareType.FirstName)); foreach (Person p in persons) { Console.WriteLine(p); } } static Person[] GetPersons() { return new Person[] { new Person { FirstName=&quot;Damon&quot;, LastName=&quot;Hill&quot; }, new Person { FirstName=&quot;Niki&quot;, LastName=&quot;Lauda&quot; }, new Person { FirstName=&quot;Ayrton&quot;, LastName=&quot;Senna&quot; }, new Person { FirstName=&quot;Graham&quot;, LastName=&quot;Hill&quot; } }; } static void SortPersons(Person[] persons) { Array.Sort(persons); foreach (Person p in persons) { Console.WriteLine(p); } } static void SortNames() { string[] names = { &quot;Christina Aguilera&quot;, &quot;Shakira&quot;, &quot;Beyonce&quot;, &quot;Gwen Stefani&quot; }; Array.Sort(names); foreach (string name in names) { Console.WriteLine(name); } } } } //SortingSample/PersonComparer.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Arrays { public enum PersonCompareType { FirstName, LastName } public class PersonComparer : IComparer<Person> { private PersonCompareType compareType; public PersonComparer(PersonCompareType compareType) { this.compareType = compareType; } #region IComparer<Person> Members public int Compare(Person x, Person y) { if (x == null) throw new ArgumentNullException(&quot;x&quot;); if (y == null) throw new ArgumentNullException(&quot;y&quot;); switch (compareType) { case PersonCompareType.FirstName: return x.FirstName.CompareTo(y.FirstName); case PersonCompareType.LastName: return x.LastName.CompareTo(y.LastName); default: throw new ArgumentException( &quot;unexpected compare type&quot;); } } #endregion } } //SortingSample/Musician.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Arrays { public class Musician : Person { } }
//YieldDemo/Program.cs using System; using System.Collections; using System.Collections.Generic; namespace Najah.ILoveCsharp.Arrays { public class HelloCollection { public IEnumerator<string> GetEnumerator() { yield return &quot;Hello&quot;; yield return &quot;World&quot;; } } class Program { static void Main() { HelloWorld(); MusicTitles(); var game = new GameMoves(); IEnumerator enumerator = game.Cross(); while (enumerator.MoveNext()) { enumerator = enumerator.Current as IEnumerator; } } static void MusicTitles() { var titles = new MusicTitles(); foreach (var title in titles) { Console.WriteLine(title); } Console.WriteLine(); Console.WriteLine(&quot;reverse&quot;); foreach (var title in titles.Reverse()) { Console.WriteLine(title); } Console.WriteLine(); Console.WriteLine(&quot;subset&quot;); foreach (var title in titles.Subset(2, 2)) { Console.WriteLine(title); } } static void HelloWorld() { var helloCollection = new HelloCollection(); foreach (string s in helloCollection) { Console.WriteLine(s); } } } } //YieldDemo/GameMoves.cs using System; using System.Collections; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Arrays { public class GameMoves { private IEnumerator cross; private IEnumerator circle; public GameMoves() { cross = Cross(); circle = Circle(); } private int move = 0; const int MaxMoves = 9; public IEnumerator Cross() { while (true) { Console.WriteLine(&quot;Cross, move {0}&quot;, move); if (++move >= MaxMoves) yield break; yield return circle; } } public IEnumerator Circle() { while (true) { Console.WriteLine(&quot;Circle, move {0}&quot;, move); if (++move >= MaxMoves) yield break; yield return cross; } } } } //YieldDemo/MusicTitles.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Arrays { public class MusicTitles { string[] names = { &quot;Tubular Bells&quot;, &quot;Hergest Ridge&quot;, &quot;Ommadawn&quot;, &quot;Platinum&quot; }; public IEnumerator<string> GetEnumerator() { for (int i = 0; i < 4; i++) { yield return names[i]; } } public IEnumerable<string> Reverse() { for (int i = 3; i >= 0; i--) { yield return names[i]; } } public IEnumerable<string> Subset(int index, int length) { for (int i = index; i < index + length; i++) { yield return names[i]; } } } }
//StructuralComparison/Person.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Arrays { public class Person : IEquatable<Person> { public int Id { get; private set; } public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return String.Format(&quot;{0}, {1} {2}&quot;, Id, FirstName, LastName); } //public override bool Equals(object obj) //{ // throw new Exception(&quot;xx&quot;); // if (obj == null) throw new ArgumentNullException(&quot;obj&quot;); // return Equals(obj as Person); //} //public override int GetHashCode() //{ // return Id.GetHashCode(); //} #region IEquatable<Person> Members public bool Equals(Person other) { if (other == null) throw new ArgumentNullException(&quot;other&quot;); return this.FirstName == other.FirstName && this.LastName == other.LastName; } #endregion } } //StructuralComparison/Program.cs using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Arrays { class TupleComparer : IEqualityComparer { #region IEqualityComparer Members public new bool Equals(object x, object y) { bool result = x.Equals(y); return result; } public int GetHashCode(object obj) { return obj.GetHashCode(); } #endregion } class Program { static void Main() { var janet = new Person { FirstName = &quot;Janet&quot;, LastName = &quot;Jackson&quot; }; Person[] persons1 = { new Person { FirstName = &quot;Michael&quot;, LastName = &quot;Jackson&quot; }, janet }; Person[] persons2 = { new Person { FirstName = &quot;Michael&quot;, LastName = &quot;Jackson&quot; }, janet }; if (persons1 != persons2) Console.WriteLine(&quot;not the same reference&quot;); if (!persons1.Equals(persons2)) Console.WriteLine(&quot;equals returns false - not the same reference&quot;); if ((persons1 as IStructuralEquatable).Equals(persons2, EqualityComparer<Person>.Default)) { Console.WriteLine(&quot;the same content&quot;); } var t1 = Tuple.Create<int, string>(1, &quot;Stephanie&quot;); var t2 = Tuple.Create<int, string>(1, &quot;Stephanie&quot;); if (t1 != t2) Console.WriteLine(&quot;not the same reference to the tuple&quot;); if (t1.Equals(t2)) Console.WriteLine(&quot;equals returns true&quot;); TupleComparer tc = new TupleComparer(); if ((t1 as IStructuralEquatable).Equals(t2, tc)) { Console.WriteLine(&quot;yes, using TubpleComparer&quot;); } } } }