Lecture 7 Collectionsin C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/352837988

Collections in C#

Presentation · June 2021


DOI: 10.13140/RG.2.2.26200.83203

CITATIONS READS
0 1,509

1 author:

Tarfa Hamed
University of Mosul
38 PUBLICATIONS 263 CITATIONS

SEE PROFILE

All content following this page was uploaded by Tarfa Hamed on 30 June 2021.

The user has requested enhancement of the downloaded file.


Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Advanced Programming in C#
Lecture Seven
C# - Collections

 Collection classes are specialized classes for data storage and


retrieval.
 These classes provide support for stacks, queues, lists, and hash
tables.
 Most collection classes implement the same interfaces.
 Collection classes serve various purposes, such as allocating memory
dynamically to elements and accessing a list of items on the basis of
an index etc.
 These classes create collections of objects of the Object class, which
is the base class for all data types in C#.

1
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Various Collection Classes and Their Usage

The following are the various commonly used classes of


the System.Collection namespace.

No. Class & Description and Useage


ArrayList

• It represents ordered collection of an object that can


be indexed individually.
• It is basically an alternative to an array. However, unlike
array you can add and remove items from a list at a
specified position using an index and the array resizes itself
automatically.
• It also allows dynamic memory allocation, adding,
searching and sorting items in the list.

Hashtable

• It uses a key to access the elements in the collection.


• A hash table is used when you need to access elements by
using key, and you can identify a useful key value. Each
item in the hash table has a key/value pair. The key is used
to access the items in the collection.

SortedList

• It uses a key as well as an index to access the items in a list.


• A sorted list is a combination of an array and a hash table.
• It contains a list of items that can be accessed using a key or
an index.
• If you access items using an index, it is an ArrayList, and if
2
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

you access items using a key , it is a Hashtable.


• The collection of items is always sorted by the key value.

Stack

• It represents a last-in, first out collection of object.


• It is used when you need a last-in, first-out access of items.
• When you add an item in the list, it is called pushing the
item and when you remove it, it is called popping the item.

Queue

• It represents a first-in, first out collection of object.


• It is used when you need a first-in, first-out access of items.
• When you add an item in the list, it is called enqueue and
when you remove an item, it is called deque.

BitArray

• It represents an array of the binary representation using the


values 1 and 0.
• It is used when you need to store the bits but do not know
the number of bits in advance.
• You can access items from the BitArray collection by using
an integer index, which starts from zero.

3
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Array Pros and Cons

• One limitation of array is that it is static in size.


• If an array is defined with size 4, then you cannot assign a value to an
index beyond 3 of that array.
• If you do, it’ll result in run-time error.

// Arrays are type-safe

int[] myArray = new int[4];

myArray[0] = 101;

myArray[1] = 102;

myArray[2] = 103;

myArray[3] = 104;

myArray[4] = 105; // run-time error -


IndexOutOfRangeException

4
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

ArrayList

• ArrayList is an alternative to arrays.


• Items can be added and removed dynamically, and the ArrayList
resizes itself.
• ArrayList belongs to System.Collections namespace.
• Add() method can be used to add items.

ArrayList myArrayList = new ArrayList();

myArrayList.Add(10);

myArrayList.Add(20);

myArrayList.Add(30);

myArrayList.Add(40);

Properties of ArrayList Class

No. Property & Description

1. Capacity

Gets or sets the number of elements that the ArrayList can


contain.
2. Count

Gets the number of elements actually contained in the


ArrayList.

5
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

3. IsFixedSize

Gets a value indicating whether the ArrayList has a fixed


size.
4. IsReadOnly

Gets a value indicating whether the ArrayList is read-only.


5. Item

Gets or sets the element at the specified index.

Methods of ArrayList Class

No. Method & Description

1. public virtual int Add(object value);


Adds an object to the end of the ArrayList.
2. public virtual void Reverse();
Reverses the order of the elements in the ArrayList.
3. public virtual void Clear();
Removes all elements from the ArrayList.
4. public virtual bool Contains(object item);
Determines whether an element is in the ArrayList.
5. public virtual int IndexOf(object);
Returns the zero-based index of the first occurrence of a
value in the ArrayList or in a portion of it.
6. public virtual void Insert(int index, object value);
Inserts an element into the ArrayList at the specified index.
7. public virtual void Remove(object obj);
Removes the first occurrence of a specific object from the
ArrayList.

6
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

8. public virtual void RemoveAt(int index);


Removes the element at the specified index of the
ArrayList.
9. public virtual void RemoveRange(int index, int count);
Removes a range of elements from the ArrayList.
10. public virtual void Sort();
Sorts the elements in the ArrayList.
Important: In order to use the ArrayList in the program, we must use
System.Collections at the beginning of the program.

ArrayList Example

ArrayList al = new ArrayList();

Console.WriteLine("Adding some numbers:");

al.Add(45);

al.Add(78);

al.Add(33);

al.Add(56);

al.Add(12);

al.Add(23);

al.Add(9);

Console.WriteLine("Capacity: "+ al.Capacity);

7
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Console.WriteLine("Count: "+ al.Count);

Console.Write("Content: ");

foreach (int i in al)

Console.Write(i + " ");

Console.WriteLine();

Console.Write("Sorted Content: ");

al.Sort();

foreach (int i in al)

Console.Write(i + " ");

8
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

ArrayList Example

• When the above code is compiled and executed, it produces the


following result:

Adding some numbers:

Capacity: 8

Count: 7

Content: 45 78 33 56 12 23 9

Content: 9 12 23 33 45 56 78

ArrayList Pros and Cons

• ArrayList is not type-safe.

• The Add() method of ArrayList accepts a parameter of type object.

• This means an item of any type can be added to ArrayList, which later
could result in run-time exception.

ArrayList myArrayList = new ArrayList();

myArrayList.Add(10);

myArrayList.Add(20);

myArrayList.Add(30);

myArrayList.Add(40);

9
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

myArrayList.Add("hello"); // could result in


run-time error

ArrayList Pros and Cons

• Another issue with ArrayList is performance degradation.

• ArrayList stores objects; the Add() method is defined to require an


object as a parameter, so an integer type is boxed.

• When a value from an ArrayList is retrieved, unboxing occurs


when the object is converted to an integer type.

• While retrieving items from ArrayList, casting is required.

• Warning: Do not use ArrayList.

ArrayList myArrayList = new ArrayList();

myArrayList.Add(44); // boxing — convert a


value type to a reference type

int num = (int)myArrayList[0]; // unboxing —


convert a reference type to a value type

Generic Collections

• A generic collection is strongly typed (type-safe).

• Meaning that you can only put one type of object into it.

10
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

• This eliminates type mismatches at runtime.

• Another benefit of type safety is that performance is better as there is


no boxing or unboxing.

• There is no overhead of converting to and from type object.

• Generic collections belongs to System.Collections.Generics


namespace.

• Few generic collection classes are:

• List

• Dictionary

• Queue

• Stack

• Linked List

• Sorted List

• Sets

Dictionary<TKey, TValue> Generic Collection

• A Dictionary stores Key-Value pairs where the key must be unique.

• TKey denotes the type of key and TValue is the type of value.

• A C# Dictionary is similar to Java’s HashMap.

11
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

• Before adding a KeyValuePair into a dictionary, check that the key


does not exist using the ContainsKey() method.

• Use a foreach or for loop to iterate a dictionary.

• Use dictionary indexer to access individual item.

Dictionary<int, string> myDictionary = new


Dictionary<int, string>();

Dictionary<TKey, TValue> Generic Collection

Important: In order to use the Dictionary collection in the program, we


must use System.Collections.Generic at the beginning of the program.

• Following are two examples of creating a dictionary.

Dictionary<int, string> myDictionary = new


Dictionary<int, string>();

// Or

Dictionary Example

Dictionary<int, string> myDictionary = new


Dictionary<int, string>()

{1, "One"},

{2, "Two"},

12
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

{3, "Three"}

};

Dictionary<TKey, TValue> Properties

Property Description
Gets the total number of elements exists in the
Count
Dictionary<TKey,TValue>.
Returns a boolean indicating whether the
IsReadOnly
Dictionary<TKey,TValue> is read-only.

Gets or sets the element with the specified key in the


Item
Dictionary<TKey,TValue>.

Returns collection of keys of


Keys
Dictionary<TKey,TValue>.
Returns collection of values in
Values
Dictionary<TKey,TValue>.

Dictionary<TKey, TValue> Methods

Method Description
void Add(TKey key, Add key-value pairs in Dictionary<TKey,
TValue value) TValue> collection.
Removes the first occurance of specified item
void Remove(T item)
from the Dictionary<TKey, TValue>.
void Remove(TKey) Removes the element with the specified key.
bool
Checks whether the specified key exists in
ContainsKey(TKey
Dictionary<TKey, TValue>.
key)

13
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

bool
Checks whether the specified key exists in
ContainsValue(TValue
Dictionary<TKey, TValue>.
value)
Removes all the elements from
void Clear()
Dictionary<TKey, TValue>.

Add Elements into Dictionary

• Use Add() method to add the key-value pair in dictionary.

• Add() Signature: void Add(TKey, Tvalue)

Example:

Dictionary<int, string> myDictionary = new


Dictionary<int, string>();

myDictionary.Add(1, "One");

myDictionary.Add(2, "Two");

myDictionary.Add(3, "Three");

Access Dictionary Collection

• Dictionary can be used like an array to access its individual elements.

• Specify key (not index) to get a value from a dictionary using indexer
like an array.

14
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Console.WriteLine(myDictionary[1]); //
returns One

Console.WriteLine(myDictionary[2]); //
returns Two

• Indexer takes the key as a parameter.

• If the specified key does not exist, then a KeyNotFoundException will


be thrown.

• It is a good idea to check if a key exists before retrieving the item.

if (myDictionary.ContainsKey(2))

// do something

Loop Through Dictionary Collection

• Use foreach or for loop to iterate all the elements of dictionary.

• The dictionary stores key-value pairs.

• So you can use a KeyValuePair<TKey, TValue> type or an implicitly


typed variable var in foreach loop.

15
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

foreach (KeyValuePair<int, string> item in


myDictionary)

Console.WriteLine("Key: " + item.Key);

Console.WriteLine("Value: " + item.Value);

foreach (var item in myDictionary)

Console.WriteLine("Key: " + item.Key);

Console.WriteLine("Value: " + item.Value);

Example:

Dictionary<string, string> cities = new


Dictionary<string, string>(){

{"UK", "London, Manchester, Birmingham"},


{"USA", "Chicago, New York, Washington"},

{"India", "Mumbai, New Delhi, Pune"}

};

16
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

foreach (var kvp in cities)

Console.WriteLine("Key: " + kvp.Key + " Value: "


+ kvp.Value);

Queue<T> Generic Collection

• A queue is a collection whose elements are processed first-in-first-


out (FIFO).

• Meaning the item that is put first in the queue is read first.

• Examples of queues are:

• standing in line at the airport,

• a human resources queue to process employee applicants,

• print jobs waiting to be processed in a print queue.

• A queue is implemented with the Queue<T> class in the


namespace System.Collections.Generic.

• You cannot access the queue elements using an indexer.

• The queue just allows you to add an item to it, which is put at the
end of the queue (with the Enqueue method), and to get items
from the beginning of the queue (with the Dequeue method).

17
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

• The Enqueue method adds items to one end of the queue; the items
are read and removed at the other end of the queue with the
Dequeue method.

• Invoking the Dequeue method once more removes the next item
from the queue.

Queue<T> Members

Members Description
Count Returns the number of items in the queue.
Enqueue Adds an item to the end of the queue.
Reads and removes an item from the head of the
queue. If there are no more items in the queue when
Dequeue
the Dequeue method is invoked, an exception of type
InvalidOperationException is thrown.
Reads an item from the head of the queue but does
Peek
not remove the item.

Add Elements into Queue

• Use the Enqueue() method to add an element to the end of the queue.

• The following example adds int values into a Queue<T> of int type.

18
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Queue<int> myQueue = new Queue<int>();

myQueue.Enqueue(10);

myQueue.Enqueue(20);

myQueue.Enqueue(30);

myQueue.Enqueue(40);

Remove Elements from Queue

• Use the Dequeue() method to remove an element from the head of


the queue.

int num = myQueue.Dequeue(); // returns 10

• Use the Peek() method to read the element from the head of the
queue, without removing it.

int num = myQueue.Peek();

Count Elements in a Queue

• Use the Count property to get the total number of elements in the
queue.

int total = myQueue.Count;

Loop Through Queue

• Use a foreach loop:

foreach (var item in myQueue)

19
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Console.WriteLine(item);

Example:

Queue<int> myQueue = new Queue<int>();

myQueue.Enqueue(10);

myQueue.Enqueue(20);

myQueue.Enqueue(30);

myQueue.Enqueue(40)

foreach(int i in myQueue)

Console.WriteLine(i);

 When the above program is executed, the output will be:

10

20

30

40

20
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Stack<T> Generic Collection

• A stack is similar to the queue.

• You just use different methods to


access the stack.

• The item that is added last to the stack


is read first, so the stack is a last-in-
first-out (LIFO) container.

• The Push method adds an item to the


stack, and the Pop method gets the
item that was added last.

Stack<T> Members

Members Description
Returns the number of items
Count
in the stack.
Adds an item on top of the
Push
stack.
Removes and returns an item
from the top of the stack. If
the stack is empty, an
Pop
exception of type
InvalidOperationException
is thrown.

21
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Returns an item from the top


Peek of the stack but does not
remove the item.
Checks whether an item is in
Contains the stack and returns true if it
is.

Add Elements into Stack

• Use the Push() method to add an element to the top of the stack.

Stack<int> myStack = new Stack<int>();

myStack.Push(10);

myStack.Push(20);

myStack.Push(30);

myStack.Push(40);

Remove Elements from Stack

• Use the Pop() method to remove an element from the top of the
stack.

int num = myStack.Pop(); // returns 40

• Use the Peek() method to read the element from the top of the
stack, without removing it.

int num = myStack.Peek();


22
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Count Elements in a Stack

• Use the Count property to get the total number of elements in the
stack.

int total = myStack.Count;

Loop Through Stack

• Use a foreach loop:

foreach (var item in myStack)

Console.WriteLine(item);

Example:

Stack<int> myStack = new Stack<int>();

myStack.Push(10);

myStack.Push(20);

myStack.Push(30);

myStack.Push(40);

foreach(int i in myStack)

Console.WriteLine(i);

}
23
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

 When the above program is executed, the output will be:

40

30

20

10

Exercise: Reversing a Line of Text with a Stack:

Write a program that inputs a line of text and uses a stack object to
display the line reversed.

Exercise: Palindromes:

Write a program that uses a stack to determine whether a string is a


palindrome (i.e., the string is spelled identically backward and forward).

The program should ignore capitalization, spaces and punctuation.

Exercise: Reversing a Line of Text with a Stack:

Write a program that reads a positive integer and prints the binary
representation of that integer.

Hint: Divide the integer by 2 and push the remainder onto stack.

24

View publication stats

You might also like