csharp4 arrays and_tuples
DESCRIPTION
TRANSCRIPT
Abed El-Azeem Bukhari (MCPD,MCTS and MCP)el-bukhari.com
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
Simple Arraysarray declaration:
int[] myArray;array initialization:
myArray = new int[4];int[] myArray = new int[4];int[] myArray = new int[] {4, 7, 11, 2};
int[] myArray = {4, 7, 11, 2};
accessing array elementsint[] myArray = new int[] {4, 7, 11, 2};int v1 = myArray[0]; // read first elementint v2 = myArray[1]; // read second elementmyArray[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);}
using reference Typespublic 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];
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"}};
multidimensional arraysint[,] 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;// orint[,] twodim = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};
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]);
jagged arraysint[][] 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 };
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: 1row: 0, element: 1, value: 2row: 1, element: 0, value: 3row: 1, element: 1, value: 4row: 1, element: 2, value: 5row: 1, element: 3, value: 6row: 1, element: 4, value: 7row: 1, element: 5, value: 8row: 2, element: 1, value: 9row: 2, element: 2, value: 10row: 2, element: 3, value: 11
Array ClassCreating 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 arrayint[] intArray2 = (int[])intArray1;
Sample1/Program.cs
Copying arraysint[] 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.
sortingstring[] names = {“Zaid",“Bashar",“Hamza",“Abed"};
Array.Sort(names);foreach (var name in names){Console.WriteLine(name);}
sortingstring[] names = {“Zaid",“Bashar",“Hamza",“Abed"};
Array.Sort(names);foreach (var name in names){Console.WriteLine(name);}
SortingSample/Person.csSortingSample/Program.csSortingSample/PersonComparer.csSortingSample/Musician.cs
arrays as Parametersstatic void DisplayPersons(Person[] persons){}
Array CovarianceFor 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.
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
Arraysegment < T > contint[] 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);
EnumerationsYieldDemo/Program.csYieldDemo/GameMoves.csYieldDemo/MusicTitles.cs
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.
NET 4.0 : System.Tuple cont
var squaresList = Tuple.Create(1, 4, 9, 16, 25, 36, 49, 64);
Console.WriteLine("1st item: {0}", squaresList.Item1); Console.WriteLine("4th item: {0}", squaresList.Item4); Console.WriteLine("8th item: {0}", squaresList.Rest);
NET 4.0 : System.Tuple cont
var tupleWithMoreThan8Elements = System.Tuple.Create("is", 2.3, 4.0f, 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);
Structural ComparisonBoth arrays and tuples implement the interfaces IStructuralEquatable and IStructuralComparable.
StructuralComparison/Person.csStructuralComparison/Program.cs
Thanks For Attending
Abed El-Azeem Bukhari (MCPD,MCTS and MCP)
el-bukhari.com