Oop Iust 10
Oop Iust 10
Data Structures
2018-2019
All slides are distributed under the Creative Commons Attribution-ShareAlike License:
Dr. R. Al King & Dr. M. H. Alsibai 3 Dr. R. Al King & Dr. M. H. Alsibai 4
Classes and Structures have the following basic differences − A C# array is basically a list of objects.
The nature of an array allows for a fast access to elements based on their
◦ classes are reference types and structs are value types position within the list (index).
◦ structures do not support inheritance A C# array is defined like this:
◦ structures cannot have default constructor
[object type][] myArray = new [object type][number of elements]
Examples:
int[] myIntArray = new int [5];
int[] myIntArray2 = { 0, 1, 2, 3, 4 };
Dr. R. Al King & Dr. M. H. Alsibai 5 Dr. R. Al King & Dr. M. H. Alsibai 6
using System;
namespace ArrayApplication
{
Output
class MyArray
int [ ] table = new int [5]; { Element[0] = 100
Element[1] = 101
table [0] = -458; static void Main(string[] args)
Element[2] = 102
{ Element[3] = 103
table [4] = 5891; int[] n = new int[10]; /* n is an array of 10 integers */ Element[4] = 104
int i, j; Element[5] = 105
table [5] = 72; // Error for (i = 0; i < 10; i++) /* initialize elements of array n */
Element[6]
Element[7]
=
=
106
107
{ Element[8] = 108
n[i] = i + 100; Element[9] = 109
for (int i = 0 ; i<= table.Length-1; i++) }
for (j = 0; j < 10; j++) /* output each array element's value */
table [i] = 3*i-1; {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}
Dr. R. Al King & Dr. M. H. Alsibai 9 Dr. R. Al King & Dr. M. H. Alsibai 10
using System;
namespace ArrayApplication
{
Output
class MyArray
{ Element[0] = 100
Element[1] = 101
static void Main(string[] args)
Element[2] = 102
{ Element[3] = 103
int[] n = new int[10]; /* n is an array of 10 integers */ Element[4] = 104
for (int i = 0; i < 10; i++) /* initialize elements of array n */ Element[5] = 105
Element[6] = 106
{
Element[7] = 107
n[i] = i + 100; Element[8] = 108
} Element[9] = 109
foreach (int j in n) /* output each array element's value */
{
int i = j - 100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}
Dr. R. Al King & Dr. M. H. Alsibai 11 Dr. R. Al King & Dr. M. H. Alsibai 12
C# allows multidimensional arrays. Multi-dimensional arrays are
also called rectangular array. You can declare a 2-dimensional
array of strings as
string [ , ] names;
or, a 3-dimensional array of int variables as Multidimensional arrays may be initialized by specifying bracketed
int [ , , ] m; values for each row. The Following array is with 3 rows and each row
Following is a 2-dimensional array, which contains 3 rows and 4 has 4 columns.
columns Thus, every element in the array a is identified by an
element name of the form a[ i , j ], where a is the name of the array, int [,] a = new int [3,4] {
and i and j are the subscripts that uniquely identify each element in
array a. {0, 1, 2, 3} , /* row indexed by 0 */
{4, 5, 6, 7} , /* row indexed by 1 */
{8, 9, 10, 11} /* row indexed by 2 */
}
Dr. R. Al King & Dr. M. H. Alsibai 13 Dr. R. Al King & Dr. M. H. Alsibai 14
}
Dr. R. Al King & Dr. M. H. Alsibai 15 Dr. R. Al King & Dr. M. H. Alsibai 16
Methods of the Array Class
◦ Clear: Sets a range of elements in the Array to zero, to false, or to null,
depending on the element type.
The Array class is the base class for all the arrays in C#. ◦ Copy(Array, Array, Int32): Copies a range of elements from an Array
Properties of the Array Class starting at the first element and pastes them into another Array
starting at the first element. The length is specified as a 32-bit integer.
◦ IsFixedSize: Gets a value indicating whether the Array has a fixed size.
◦ CopyTo(Array, Int32): Copies all the elements of the current one-
◦ IsReadOnly: Gets a value indicating whether the Array is read-only.
dimensional Array to the specified one-dimensional Array starting at
◦ Length: Gets a 32-bit integer that represents the total number of the specified destination Array index. The index is specified as a 32-
elements in all the dimensions of the Array. bit integer.
◦ LongLength: Gets a 64-bit integer that represents the total number of ◦ GetLength: Gets a 32-bit integer that represents the number of
elements in all the dimensions of the Array. elements in the specified dimension of the Array.
◦ Rank: Gets the rank (number of dimensions) of the Array. ◦ GetLowerBound: Gets the lower bound of the specified dimension in
the Array.
Dr. R. Al King & Dr. M. H. Alsibai 19 Dr. R. Al King & Dr. M. H. Alsibai 20
◦ GetType: Gets the Type of the current instance. (Inherited from Object.)
◦ GetUpperBound: Gets the upper bound of the specified dimension in
the Array.
◦ GetValue(Int32): Gets the value at the specified position in the one- Useful properties and methods
dimensional Array. The index is specified as a 32-bit integer.
◦ IndexOf(Array, Object): Searches for the specified object and returns ◦ Length: total number of elements
the index of the first occurrence within the entire one-dimensional ◦ Rank: total number of dimensions
Array. ◦ GetLength (int): number of elements in the specified dimension
◦ Reverse(Array): Reverses the sequence of the elements in the entire To iterate through a rectangular array
one-dimensional Array.
◦ Sort(Array): Sorts the elements in an entire one-dimensional Array for(int i=0; i<a.GetLength(0); i++)
using the IComparable implementation of each element of the Array. for(int j=0; j<a.GetLength(1); j++)
◦ ToString: Returns a string that represents the current object. (Inherited
from Object.)
{ /*Work with a[i,j]*/ }
Dr. R. Al King & Dr. M. H. Alsibai 21 Dr. R. Al King & Dr. M. H. Alsibai 22
Dr. R. Al King & Dr. M. H. Alsibai 25 Dr. R. Al King & Dr. M. H. Alsibai 26
Collection classes are specialized classes for data storage and Generics were added to version 2.0 of the C# language and the
retrieval. These classes provide support for stacks, queues, common language runtime (CLR).
lists, and hash tables. Use generic types to maximize code reuse, type safety, and
performance.
Most collection classes implement the same interfaces. The most common use of generics is to create collection classes.
Collection classes serve various purposes, such as allocating The .NET Framework class library contains several new generic
memory dynamically to elements and accessing a list of items collection classes in the System.Collections.Generic namespace.
on the basis of an index etc. These are used whenever possible instead of classes such as
ArrayList in the System.Collections namespace.
These classes create collections of objects of the Object class,
You can create your own generic interfaces, classes, methods,
which is the base class for all data types in C#. events and delegates.
Dr. R. Al King & Dr. M. H. Alsibai 27 Dr. R. Al King & Dr. M. H. Alsibai 28
The C# data structure, ArrayList, is a dynamic array.
ArrayList can have any amount of objects and of any type.
We cover the following Collection classes in this course. All of them are This data structure was designed to simplify the processes of adding new
members of the namespace: System.Collection or elements into an array.
System.Collections.Generic as they belong to Data Structures: ArrayList is an array whose size is doubled every time it runs out of space.
◦ ArrayList
◦ List<T> ArrayList myArrayList = new ArrayList();
◦ LinkedList<> myArrayList.Add(56);
◦ Dictionary myArrayList.Add("String");
◦ HashSet myArrayList.Add(new Form());
◦ Stack
The downside to the ArrayList data structure is one must cast the retrived
◦ Queue values back into their original type:
To use the above data structures we need to add
int arrayListValue = (int)myArrayList[0];
using System.Collections; or
using System.Collections.Generic;
Dr. R. Al King & Dr. M. H. Alsibai 29 Dr. R. Al King & Dr. M. H. Alsibai 30
Dr. R. Al King & Dr. M. H. Alsibai 31 Dr. R. Al King & Dr. M. H. Alsibai 32
using System;
A LinkedList is a series of objects which instead of having their references indexed (like an Array),
stay together by linking to each other, in Nodes.
using System.Collections.Generic;
A LinkedList Node has basically three values: the Object's Value, a reference to the Next node, and a
reference to the Previous Node.
class Test Adding values to the middle of the list is much faster compared to any other Array type of data
{ structure. It also keeps memory costs down to a minimum. Lists on the other hand use extra space to
static void Main() Output make future insertions as fast as possible.
{ 34 LinkedList<int> list = new LinkedList<int>();
List<int> intList = new List<int>(); Press any key to continue . . . list.AddLast(6);
intList.Add(45);
intList.Add(34);
Retrieving a value is not as straight forward:
intList.Add(66);
list.First.Value or
int listValue = intList[1]; list.Last.Value
Console.WriteLine(listValue);
Since inserting and removing elements is done by updating a couple references, they can be done in
constant time. The tradeoff is that accessing elements is no longer a constant time operation. In an
} array, with a given index an element can be instantly accessed. With a linked list, the references
} between nodes need to be followed until the desired element is found.
Dr. R. Al King & Dr. M. H. Alsibai 33 Dr. R. Al King & Dr. M. H. Alsibai 34
using System;
using System.Collections.Generic;
Dr. R. Al King & Dr. M. H. Alsibai 35 Dr. R. Al King & Dr. M. H. Alsibai 36
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
class Test class Test
{ {
static void Main() static void Main() Output
{ Output { one
Dictionary<string, int> myDictionary = new Dictionary<string, int>(); 20 Dictionary<int, string> myDictionary = new Dictionary<int , string>(); Dog
myDictionary.Add("one", 1); 7 myDictionary.Add(1,"one"); Press any key to continue . . .
Press any key to continue . . .
myDictionary.Add("twenty", 20); myDictionary.Add(20, "twenty");
myDictionary.Add("Dog", 7); myDictionary.Add(7,"Dog");
Dr. R. Al King & Dr. M. H. Alsibai 37 Dr. R. Al King & Dr. M. H. Alsibai 38
The reason is speed. A C# Hashtable stores items faster than a C# HT.Add(3, "Cat"); }
HT.Add(4, "Dolphine"); }
Dictionary, which sacrifices speed for the sake of order.. HT.Add(2, "Goat");
HT.Add(5, "Sheep");
Dr. R. Al King & Dr. M. H. Alsibai 39 Dr. R. Al King & Dr. M. H. Alsibai 40
Output
The HashSet data structure was introduced in C#.NET 3.5. This particular C#
Keys are:
5
data structure very strongly resembles the List<> data strucuture.
4 A HashSet has the very important characteristic that it does not allow duplicate
3 values. For example:
2
1 HashSet<int> mySet = new HashSet<int>();
Values are: mySet.Add(3);
Sheep
Dolphine mySet.Add(5);
Cat mySet.Add(3);
Goat mySet.Add(10);
Dog
List<int> myListFromSet = mySet.ToList<int>();
int myInt = myListFromSet[2];
keys and associated Values are:
keys=5 values=Sheep
keys=4 values=Dolphine If mySet were a regular List data structure, the index 2 should return the value 3
keys=3 values=Cat (count it out). But if you run the example you will see that myInt actually returns
keys=2 values=Goat
keys=1 values=Dog
the value 10. This is because the HashSet C# data structure ignored the
duplicate addition of the value 3.
Dr. R. Al King & Dr. M. H. Alsibai 41 Dr. R. Al King & Dr. M. H. Alsibai 42
makes sure the element doesn't already exist. However a HashSet } }//Main
firstset.Contains(45));
is not a simple array, it is specifically designed to allow fast search Console.WriteLine("The table of five(5) is:"); } // Program
times which dramatically improves the performace of checking foreach (int a in firstset) } // namespace
whether a new element is a duplicate or not. {
Console.WriteLine(a);
}
Dr. R. Al King & Dr. M. H. Alsibai 43 Dr. R. Al King & Dr. M. H. Alsibai 44
Output The Stack class is one of the important structures that resembles
The table of five(5) is: an List.
5
10 To add to a stack data structure, we use Push method,
15
20
Retrieving a value we use Pop which returns and removes the last
25 object added.
30
35 To check the top value in a Stack without removing it, we use the
40
45 Peek method.
50
After Removal elements hashset is:
Stack is a LIFO structure (Last-In-First-Out)
40
45
We define a Stack in C# like this:
50
ITem contain 15 is:False
ITem contain 45 is:True
Press any key to continue . . . Stack<string> stack = new Stack<string>();
Dr. R. Al King & Dr. M. H. Alsibai 45 Dr. R. Al King & Dr. M. H. Alsibai 46
Here is the C# code to add and traverse through a Stack data structure:
using System; Another one of the important structures is the Queue.
using System.Collections.Generic;
A Queue is very similar to the Stack BUT Queue is FIFO (First-
class Test In-First-Out). i.e. The first objects added are the first ones to
{ be processed.
static void Main()
{
Output To Add (Push) object to queue we use Enqueue:
3
Stack<string> stack = new Stack<string>();
stack.Push("1");
2 queue.Enqueue("1");
1
stack.Push("2"); Press any key to continue . . .
stack.Push("3"); The Remove an object we call Dequeue:
while (stack.Count > 0) queue.Dequeue();
{
Console.WriteLine(stack.Pop());
} Similarly the Peek method retunes the top value without
} removing it.
}
Dr. R. Al King & Dr. M. H. Alsibai 47 Dr. R. Al King & Dr. M. H. Alsibai 48
Here is some simple C# code to add items to a queue and the transverse it:
using System;
using System.Collections.Generic;
Dr. R. Al King & Dr. M. H. Alsibai 49 Dr. R. Al King & Dr. M. H. Alsibai 50
Language-Integrated Query (LINQ) is a powerful query language Query expressions are written in a declarative query syntax.
introduced with .Net 3.5 & Visual Studio 2008.
LINQ can be used with C# or Visual Basic to query different data By using query syntax, you can perform filtering, ordering,
sources. and grouping operations on data sources with a minimum of
Language-Integrated Query (LINQ) is the name for a set of code.
technologies based on the integration of query capabilities directly
into the C# language. You use the same basic query expression patterns to query
Traditionally, you have to learn a different query language for each and transform data in SQL databases, ADO .NET Datasets,
type of data source: SQL databases, XML documents, various Web XML documents and streams, and .NET collections.
services, and so on.
With LINQ, a query is a first-class language construct, just like
classes, methods, events.
Dr. R. Al King & Dr. M. H. Alsibai 51 Dr. R. Al King & Dr. M. H. Alsibai 52
using System; Reference:
using System.Collections.Generic;
using System.Linq;
https://www.tutorialspoint.com/csharp/
namespace ConsoleApplication2{ Michael McMillan, “Data Structures and Algorithms Using C#”,
class LINQQueryExpressions{
static void Main(){
Cambridge University Press , 2007
int[] scores = new int[] { 97, 92, 81, 60 }; Thank you for your attention
// Define the query expression.
IEnumerable<int> scoreQuery =
from score in scores Documents related to this class are on:
where score > 80
select score; http://bit.ly/OOP_IUST
// Execute the query.
FB: https://www.facebook.com/Mhdhayyan.alsibai
foreach (int i in scoreQuery) {
Console.Write(i + " ");
}
} // Main( )
Any question?
} //class
// Output: 97 92 81
}//namespace
Dr. R. Al King & Dr. M. H. Alsibai 53 Dr. R. Al King & Dr. M. H. Alsibai 54