7.collection Classes (Final)
7.collection Classes (Final)
Studies
Chapter (6)
Collection Classes
1
Contents
Array Class
Properties and Methods in Array Hashtable
Class Properties and Method in Hashtable
SortedList
2
Properties and Method in SortedList
Array Class
store multiple values in a single variable, instead of declaring separate variables for each
value
stores a fixed-size sequential collection of elements of the same type
two kinds of arrays in C#
Normal Array:
3
Array Class
another kind of array provided by Array
class
the base class for all the arrays in C#
defined in the System namespace
Example
4
Properties and Methods in Array Class
Table 1
Property Description
IsFixedSize Gets a value indicating whether the Array has a fixed size
Length Gets a 32-bit integer that represent the total number of elements in all the dimensions of the
Array
LongLength Gets a 64-bit integer that represent the total number of elements in all the dimensions of
the Array
5
Properties and Methods in Array Class
Table 2
Method Description
Clear( ) Sets a range of elements in the Array to zero, to false, or to null, depending on the
element type
Copy(Array, Array,Int32) Copies a range of elements from an Array 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.
CopyTo(Array, Int32) Copies all the elements of the current one-dimensional Array to the specified one-
dimensional Array starting at the specified destination Array index. The index is
specified as a 32-bit integer.
GetLength(dimension) Gets a 32-bit integer that represents the number of elements in the specified dimension of
the Array
GetLongLength(dimension) Gets a 64-bit integer that represents the number of elements in the specified dimension
of the Array
GetLowerBound(dimension) Gets the lower bound of the specified dimensions in the Array
6
Properties and Methods in Array Class
Table 3
Method Description
GetUpperBound(dimension) Gets the upper bound of the specified dimension in the Array. The index is specified as a 32-bit
integer.
GetValue(Int32) Gets the value at the specified position in the one-dimensional Array. The index is specified as
32-bit integer
IndexOf(Array, Object) Searches for the specified object and returns the index of the first occurrence within the
entire one-dimensional Array
Reverse(Array) Reverse the sequence of the elements in the entire one-dimensional Array
SetValue(Object, Int32) Sets a value to the element at the specified position in the one-dimensional Array. The index is
specified as 32-bit integer
Sort(Array) Sorts the elements in an entire one-dimensional Array using the IComparable implementation of
each element of the Array
ToString( ) Returns a string that represents the current object. (Inherited from Object)
7
Quiz
Quiz
Quiz
Quiz
Quiz
Quiz
Limitations of Array in C#
{ Console.WriteLine("Using ArrayList");
int[] n = new int [3]; ArrayList arr = new ArrayList();
n[0] = 1; arr.Add(1);
n[1] = 2; arr.Add(2);
n[2] = 3; arr.Add(3);
foreach(int i in n) foreach (var array in arr)
{ Console.WriteLine(array);
Console.WriteLine(i); arr.Insert(2, 5);
} foreach (var array in arr)
Console.WriteLine(array);
//bool fixedn = n.IsFixedSize;
//bool readOnlyn = n.IsReadOnly;
//Console.WriteLine(fixedn); arr.RemoveAt(2);
//Console.WriteLine(readOnlyn); foreach (var array in arr)
n[1] = 5; Console.WriteLine(array);
foreach (int i in n)
{ Console.Read();
Console.WriteLine(i); }
}
Collection Classes
store, manage and manipulate (add, remove, find, and insert) similar data more efficiently
Replacing items
Capacity and Count properties to find the capacity of the collection and number of items in the
collection
17
Collection Classes
18
Collection Classes
19
Indexed Based Collections
20
Key value paired Collections
21
Prioritized Collections
22
Types of Collections in C#
23
Collection Classes
ArrayList List
HashTable Dictionary
SortedList SortedList
Stack Stack
Queue Queue
24
ArrayList
1. The Elements can be added and removed from the Array List collection at any
point in time.
2. The ArrayList is not guaranteed to be sorted.
3. The capacity of an ArrayList is the number of elements the ArrayList can hold.
4. Elements in this collection can be accessed using an integer index. Indexes in
this collection are zero-based.
5. It allows duplicate elements.
Properties and Methods in ArrayList
Table 4
Property Description
Capacity Gets or sets the number of elements that the ArrayList can contain.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
28
Array List Example (Adding Elements in ArrayList)
Methods in ArrayList
Table 5
Method Description
Add( ) / AddRange( ) Add( ) method adds single elements at the end of ArrayList.
AddRange( ) method adds all the elements from the specified collection into ArrayList.
Insert( ) / InsertRange( ) Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() method insert all the elements of the specified collection starting
from specified index in ArrayList.
Remove()/ RemoveRange( ) Remove() method removes the specified element from the ArrayList.
RemoveRange() method removes a range of elements from the ArrayList.
RemoveAt( ) Removes the element at the specified index from the ArrayList.
Contains( ) Checks whether specified element exists in the ArrayList or not. Returns true if exists
otherwise false.
Clear( ) Removes all the elements in ArrayList.
GetRange( ) Returns specified number of elements from specified index from ArrayList.
IndexOf( ) Search specified element and returns zero based index if found. Returns -1 if element
not found.
ToArray( ) Returns compitible array from an ArrayList.
31
ArrayList
32
Properties and Methods in ArrayList
Accessing Elements
Example
ArrayList A = new ArrayList( );
A.Add(1);
A.Add("Two");
A.Add(3);
A.Add(4.5f);
33
Properties and Methods in ArrayList
"Two", 3,
Console.WriteLine(value);
foreach (var value in A)
( or )
Console.WriteLine(A[i]);
34
Array List Example
(Add entire array/ArrayList into ArrayList)
Properties and Methods in ArrayList
Inserting Elements into ArrayList
Example:
ArrayList A = new ArrayList ();
A.Add(1);
A.Add("Two");
A.Add(3);
A.Add(4.5);
Example:
ArrayList A = new
ArrayList(); A.Add(100);
A.Add(200);
ArrayList B = new
ArrayList(); B.Add(10);
B.Add(20);
B.Add(30);
B.InsertRange(2, A);
foreach(var item in B)
Console.WriteLine(item); 18
Properties and Methods in ArrayList
Remove Elements from
ArrayList
Signature: void Remove(Object )
Example:
ArrayList num = new
ArrayList(); num.Add(100);
num.Add(200);
num.Add(300);
num.Remove(100);
foreach (var item in num)
Console.WriteL
ine(item);
38
Properties and Methods in ArrayList
Example: RemoveAt()
ArrayList num = new
ArrayList(); num.Add(100);
num.Add(200);
num.Add(300);
num.RemoveAt(1);
39
Properties and Methods in ArrayList
Example:
ArrayList num = new ArrayList();
num.Add(100);
num.Add(200);
num.Add(300);
num.RemoveRange(0,2);
40
Properties and Methods in ArrayList
41
Properties and Methods in ArrayList
42
ArrayList Example
static void Main(string[] args)
{
//Adding elements to ArrayList using Add() method
ArrayList arrayList1 = new ArrayList();
arrayList1.Add(101); //Adding Integer Value
arrayList1.Add("James"); //Adding String Value
arrayList1.Add(true); //Adding Boolean
arrayList1.Add(4.5); //Adding double
//Accessing individual elements from ArrayList using Indexer
int firstElement = (int)arrayList1[0]; //returns 101
string secondElement = (string)arrayList1[1]; //returns "James"
//int secondElement = (int) arrayList1[1]; //Error: cannot cover string to int
Console.WriteLine("First Element: "+ firstElement + " Second Element: "+ secondElement);
//Using var keyword without explicit casting
var firsItem = arrayList1[0]; //returns 101
var secondItem = arrayList1[1]; //returns "James"
//var fifthElement = arrayList1[5]; //Error: Index out of range
Console.WriteLine("First Item: " + firsItem + " Second Item: "+secondItem);
//update elements
arrayList1[0] = "Smith";
arrayList1[1] = 1010;
//arrayList1[5] = 500; //Error: Index out of range
foreach (var item in arrayList1)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
List
44
Properties and Methods in List
Table 7
Properties/ Methods Description
Capacity Gets or sets the total number of elements the internal data structure can hold
without resizing.
BinarySearch( ) Uses a binary search algorithm to locate a specific element in the sorted
List<T> or a portion of it.
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line); // Add to list.
Console.WriteLine(line); // Write to console.
}
list.Reverse();
foreach (var var in list)
{
Console.WriteLine(var);
}
Console.Read();
}
Dictionary
collection of Keys and Values, where key is like word and value is like definition
50
Properties and Methods in Dictionary
Table 8
Property Description
Count Gets the total number of elements exists in the Dictionary<Tkey, Tvalue>
51
Properties and Methods in Dictionary
Table 9
Method Description
Remove( ) Removes the first occurrence of specified item from the Dictionary<TKey, TValue>
TryGetValue( ) Returns true and assigns the value with the specified key, if key does not exist
52
Properties and Methods in Dictionary
Create Dictionary and Add elements
53
Properties and Methods in Dictionary
Create Dictionary with initialization
54
Properties and Methods in Dictionary
Accessing elements in Dictionary by using for loop
55
Properties and Methods in Dictionary
Accessing Values in Dictionary
foreach
{ ( KeyValuePair<int, string> kp " + kp.Key
Console.WriteLine("Key: in dict)
+ " , " + kp.Value); }
56
Properties and Methods in Dictionary
Removing elements in Dictionary
dict.Remove(2);
dict.Remove(7);
dict.Clear();
if ( dict.ContainsValue(“pink”) )
Console.WriteLine("This value already exist"); 57
Properties and Methods in Dictionary
if (dict.ContainsKey(3))
Console.WriteLine("This key already exist");
58
SortedList
59
Properties and Methods in SortedList
Table 10
Property Description
Capacity Gets or sets the number of elements that the SortedList instance can store
IsFixedSize Gets a value indicating whether the SortedList has a fixed size
60
Properties and Methods in SortedList
Table 11
Method Description
GetKey(int index) Returns the key stored at specified index in internal array
61
Properties and Methods in SortedList
Create SortedList and Add elements
SortedList s = new SortedList( );
s.Add(3, “Red");
s.Add(4, “Pink");
s.Add(1, “Cyan");
s.Add(5, null);
s.Add(2, true);
IsReadOnly, IsFixedSize
Console.WriteLine("IsReadOnly: " + s.IsReadOnly);
Console.WriteLine("IsFixedSize: " + s.IsFixedSize);
63
Properties and Methods in SortedList
Console.Writ
Access all Values ine(x +"
SortedList
ICollection v = s.Values;
foreach ( string x in v)
{ , "); }
Console.Write
(x + "
64
Properties and Methods in SortedList
Iterate elements in SortedList by using foreach loop
s.Remove(3);
s.RemoveAt(4);
s.Clear();
67
Properties and Methods in SortedList
Copy SortedList
SortedList s1=(SortedList) s.Clone(); // create a shallow copy of sortedlist
object
// explicit conversion from object type to
SortedList
foreach (DictionaryEntry kv in s1)
{ Console.WriteLine(kv.Key + " , " + kv.Value); }
68
Properties and Methods in SortedList
69
Quiz
Quiz
Hashtable
non-generic collection type
72
Hashtable
Properties and Methods in Hashtable
Table 12
Property Description
74
Properties and Methods in Hashtable
Table 13
Method Description
Add Adds an item with a key and value into hashtable
Remove Removes the item with the specified key from hashtable
75
Properties and Methods in Hashtable
77
Properties and Methods in Hashtable
Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(value3);
78
Properties and Methods in Hashtable
ICollection k = ht.Keys;
foreach (object item in
k)
{
Console.Write(item + ",
"); }
79
Properties and Methods in Hashtable
ICollection v = ht.Values;
foreach (var item in v)
{
Console.Write(item+ ", ");
}
Remove specified element by using Key
ht.Remove(“Fv”);
ht.Clear();
80
Properties and Methods in Hashtable
if(ht.ContainsValue(“Orange”))
Console.WriteLine("Value
ready exist");
if(ht.ContainsKey(1))
Console.WriteLine(“Key ready
exist”);
81
Properties and Methods in Hashtable
Copy Hashtable
Hashtable h =(Hashtable) ht.Clone(); // convert object type to hashtable
typem
// shallow copy, return object type
foreach (DictionaryEntry item in h)
{ Console.WriteLine(item.Key + ", " + item.Value); }
Array A =
Array.CreateInstance(typeof(object),4);
ht.CopyTo(A,0);
for (int i = 0; i < A.Length; i++)
{
DictionaryEntry d = (DictionaryEntry) A.GetValue(i)
;
Console.WriteLine(d.Key + ", " + d.Value);
} 56
Differences between SortedList and Hashtable
Table 14
SoredList Hashtable
a collection of key/value pairs that are sorted by the keys a collection of key/value pairs that are organized based on
the hash code of the key
elements are accessible by key and by index elements are accessible by key
83
Stack
C# includes a special type of collection which stores elements in LIFO style (Last In First
Out).
84
Properties and Methods in Stack
Table 15
Properties/Methods Description
Count Returns the total count of elements in the Stack.
Push( ) Inserts an item at the top of the stack.
Peek( ) Returns the top item from the stack.
Pop( ) Removes and returns items from the top of the stack.
85
Properties and Methods in Stack
86
Properties and Methods in Stack
Console.WriteLine(myStack.Peek());
Console.WriteLine(myStack.Peek());
Console.WriteLine(myStack.Peek());
Queue stores the elements in FIFO style (First In First Out), exactly opposite of the Stack
collection.
88
Properties and Methods in Queue
Table 16
Properties/Methods Description
Count Returns the total count of elements in the Queue.
Dequeue( ) Removes and returns an item from the beginning of the queue.
TrimToSize( ) Sets the capacity of the queue to the actual number of items in the
queue.
89
Properties and Methods in Queue
Create Queue and Add
elements
Queue q= new Queue();
q.Enqueue(3);
q.Enqueue(2);
q.Enqueue(1);
q.Enqueue("Four");
90
Properties and Methods in Queue
Console.WriteLine(q.Peek());
Console.WriteLine(q.Peek());
Console.WriteLine(q.Peek());