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

:C#Zone

Week 7(according to IUB outline):-


---------------------------------------------------------------------------------
Programming with C# Part-I
Using various data structures: Using Arrays (One Dimensional, Two Dimensional,
Jagged), Array.
ArrayList classes
Using Collections: Collection, HashTable, List, Stack, Queue, HashSet classes.
---------------------------------------------------------------------------------
Any issue:umarfarooqworld@outlook.com
Ref: C#Corner Pick “N” Share :C#Notes

Introduction
Arrays in C# are one of the most used objects. In this article, you will learn the basics of arrays
and how to use arrays in C#.
In C#, an array index starts at zero. That means the first item of an array starts at the
0th position. The position of the last item on an array will total number of items - 1. So if an
array has 10 items, the last 10th item is at 9th position.

In C#, arrays can be declared as fixed length or dynamic.


 A fixed length array can store a predefined number of items.
 A dynamic array does not have a predefined size. The size of a dynamic
array increases as you add new items to the array. You can declare an array of fixed
length or dynamic. You can even change a dynamic array to static after it is defined.

Let's take a look at simple declarations of arrays in C#. The following code snippet defines the
simplest dynamic array of integer types that does not have a fixed size.
 int[] intArray;

As you can see from the above code snippet, the declaration of an array starts with a type of
array followed by a square bracket ([ ]) and name of the array.
The following code snippet declares an array that can store 5 items only starting from index 0
to 4.
1. int[] intArray;
2. intArray = new int[5];

 The following code snippet declares an array that can store 100 items starting from index 0 to 99.

1. int[] intArray;
2. intArray = new int[100];

Defining arrays of different types


 In the previous code snippet, we saw how to define a simple array of integer type.
Similarly, we can define arrays of any type such as double, character, and string.
 In C#, arrays are objects. That means that declaring an array doesn't create an
array. After declaring an array, you need to instantiate an array by using the "new"
operator.
 The following code snippet defines arrays of double, char, bool, and string data
types.
1. double[] doubleArray = new double[5];
2. char[] charArray = new char[5];
3. bool[] boolArray = new bool[2];
4. string[] stringArray = new string[10];

Initializing Arrays
 Once an array is declared, the next step is to initialize an array. The initialization
process of an array includes adding actual data to the array.
 The following code snippet creates an array of 3 items and values of these items are
added when the array is initialized .
1. // Initialize a fixed array
2. int[] staticIntArray = new int[3] {1, 3, 5};

2|Page “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

 Alternative, we can also add array items one at a time as listed in the following code
snippet.
1. // Initialize a fixed array one item at a time
2. int[] staticIntArray = new int[3];
3. staticIntArray[0] = 1;
4. staticIntArray[1] = 3;
5. staticIntArray[2] = 5;

 The following code snippet declares a dynamic array with string values.
1. // Initialize a dynamic array items during declaration
2. string[] strArray = new string[] { "Saqib", "Numan", "Talha", "Azeem", "Qaiser" };

Accessing Arrays
 We can access an array item by passing the item index in the array. The following
code snippet creates an array of three items and displays those items on the
console.
1. // Initialize a fixed array one item at a time
2. int[] staticIntArray = new int[3];
3. staticIntArray[0] = 1;
4. staticIntArray[1] = 3;
5. staticIntArray[2] = 5;
6. // Read array items one by one
7. Console.WriteLine(staticIntArray[0]);
8. Console.WriteLine(staticIntArray[1]);
9. Console.WriteLine(staticIntArray[2]);

This method is useful when you know what item you want to access from an array. If you try to
pass an item index greater than the items in array, you will get an error.

Accessing an array using a foreach Loop

 The foreach control statement (loop) is used to iterate through the items of an array.
For example, the following code uses foreach loop to read all items of an array of
strings.
1. // Initialize a dynamic array items during declaration
2. string[] strArray = new string[] {
3. "Saqib",
4. "Numan",
5. "Talha ",
6. "Azeem",
7. "Qaiser"
8. };
9. // Read array items using foreach loop
10. foreach(string str in strArray) {
11. Console.WriteLine(str);
12. }

This approach is used when you do not know the exact index of an item in an array and needs
to loop through all the items.

3|Page “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

Types of Array
Arrays can be divided into the following four categories.
 Single-dimensional arrays
 Multidimensional arrays or rectangular arrays
 Jagged arrays
 Mixed arrays.

Single Dimension Arrays


Single-dimensional arrays are the simplest form of arrays. These types of arrays are
used to store number of items of a predefined type. All items in a single dimension array
are stored contiguously starting from 0 to the size of the array -1.

 The following code declares an integer array that can store 3 items. As you can see
from the code, first I declare the array using [] bracket and after that I instantiate the
array by calling the new operator.
int[] intArray;
intArray = new int[3];

 Array declarations in C# are pretty simple. You put array items in curly braces ({}). If
an array is not initialized, its items are automatically initialized to the default initial
value for the array type if the array is not initialized at the time it is declared.

 The following code declares and initializes an array of three items of integer type.
int[] staticIntArray = new int[3] {1, 3, 5};

 The following code declares and initializes an array of 5 string items.


string[] strArray = new string[5] { "Saqib", "Numan", "Talha", "Azeem", "Qaiser" };

 You can even directly assign these values without using the new operator.
string[] strArray = { "Saqib", "Numan", "Talha", "Azeem", "Qaiser" };

 You can initialize a dynamic length array as follows:


string[] strArray = new string[]{ "Saqib", "Numan", "Talha", "Azeem", "Qaiser" };

Multi-Dimensional Arrays
A multi-dimensional array, also known as a rectangular array is an array with more than
one dimension. The form of a multi-dimensional array is a matrix.
Declaring a multi-dimensional array
 A multi dimension array is declared as following:
string[,] mutliDimStringArray;
 A multi-dimensional array can be fixed-sized or dynamic sized.

4|Page “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

Initializing multi-dimensional arrays

 The following code snippet is an example of fixed-sized multi-dimensional arrays that


defines two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can
store 6 items and second array can store 4 items. Both of these arrays are initialized
during the declaration.

1. int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };


2. string[,] names = new string[2, 2] { { "Ali", "Zubair" }, { "Afzal", "Andleeb" } };

 Now let's see examples of multi-dimensional dynamic arrays where you are not sure of
the number of items of the array. The following code snippet creates two multi-
dimensional arrays with no limit.

1. int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };


2. string[,] names = new string[,] { { "Numan", "Saqib" }, { "Kinza", "Pakiza" } };

 You can also omit the new operator as we did in single dimension arrays. You can assign these values
directly without using the new operator. For example:

1. int[, ] numbers = {
2. {
3. 1,
4. 2
5. },
6. {
7. 3,
8. 4
9. },
10. {
11. 5,
12. 6
13. }
14. };
15. string[, ] names = {
16. {
17. "Numan",
18. "Saqib"
19. },
20. {
21. "Kinza",
22. "Pakiza"
23. }
24. };

 We can also initialize the array items one item at a time. The following code snippet is an example of
initializing array items one at a time.

1. int[, ] numbers = new int[3, 2];


2. numbers[0, 0] = 1;
3. numbers[1, 0] = 2;
4. numbers[2, 0] = 3;
5. numbers[0, 1] = 4;
6. numbers[1, 1] = 5;
7. numbers[2, 1] = 6;

5|Page “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

Accessing multi-dimensional arrays


 A multi-dimensional array items are represented in a matrix format and to access it's
items, we need to specify the matrix dimension. For example, item(1,2) represents an
array item in the matrix at second row and third column.
 The following code snippet shows how to access numbers array defined in the above
code.
1. Console.WriteLine(numbers[0, 0]);
2. Console.WriteLine(numbers[0, 1]);
3. Console.WriteLine(numbers[1, 0]);
4. Console.WriteLine(numbers[1, 1]);
5. Console.WriteLine(numbers[2, 0]);
6. Console.WriteLine(numbers[2, 2]);

Jagged Arrays
 Jagged arrays are arrays of arrays. The elements of a jagged array are other arrays.
Declaring Jagged Arrays
 Declaration of a jagged array involves two brackets. For example, the following code
snippet declares a jagged array that has three items of an array.
int[][] intJaggedArray = new int[3][ ];
 The following code snippet declares a jagged array that has two items of an array.
string[][] stringJaggedArray = new string[2][]

Initializing Jagged Arrays


 Before a jagged array can be used, its items must be initialized. The following code
snippet initializes a jagged array; the first item with an array of integers that has two
integers, second item with an array of integers that has 4 integers, and a third item with
an array of integers that has 6 integers.

1. // Initializing jagged arrays


2. intJaggedArray[0] = new int[2];
3. intJaggedArray[1] = new int[4];
4. intJaggedArray[2] = new int[6];

 We can also initialize a jagged array's items by providing the values of the array's items.
The following code snippet initializes item an array's items directly during the
declaration.

1. // Initializing jagged arrays


2. intJaggedArray[0] = new int[2] {
3. 2,
4. 12
5. };
6. intJaggedArray[1] = new int[4] {
7. 4,
8. 14,
9. 24,
10. 34
11. };
12. intJaggedArray[2] = new int[6] {
13. 6,
14. 16,
15. 26,
16. 36,
17. 46,
18. 56
19. };

6|Page “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

Complete Example
1. Console.WriteLine("Single Dimension Array Sample");
2. // Single dim array
3. string[] strArray = new string[] ] {
4. "Saqib",
5. "Numan",
6. "Talha",
7. "Azeem",
8. "Qaiser"
9. };
10. // Read array items using foreach loop
11. foreach(string str in strArray) {
12. Console.WriteLine(str);
13. }
14. Console.WriteLine("-----------------------------
-----------------------------");
15. Console.WriteLine("Multi-Dimension
Dimension Array Sample");
16. string[, ] string2DArray = new string[2, 2] {
17. {
18. "Saqib",
19. "Numan"
20. }, {
21. "Kinza",
22. "Pakiza"
23. }
24. };
25. foreach(string str in string2DArray) {
26. Console.WriteLine(str);
27. }
28. Console.WriteLine("-----------------------------
-----------------------------");
29. Console.WriteLine("Jagged Array Sample");
30. int[][] intJaggedArray3 = {
31. new int[] {
32. 2,
33. 12
34. },
35. new int[] {
36. 14,
37. 14,
38. 24,
39. 34
40. },
41. new int[] {
42. 6,
43. 16,
44. 26,
45. 36,
46. 46,
47. 56
48. }
49. };
50. // Loop through all itesm of a jagged array
51. for (int i = 0; i < intJaggedArray3.Length; i++) {
52. Console.Write("Element({0}):
"Element({0}): ", i);
53. for (int j = 0; j < intJaggedArray3[i].Length; j++) {
54. Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length -
1) ? "" : " ");
55. }
56. Console.WriteLine();
57. }
58. Console.WriteLine("-----------------------------
--------------------------");
Ref: C#Corner Pick “N” Share :C#Notes

ArrayList
Introduction
ArrayList implements the IList interface using an array whose size is dynamically
increased as required. In this article I explain how to create the ArrayList and the
various methods and properties of the ArrayList.
Creation of ArrayList

To create the ArrayList the following code is used:

ArrayList arr = new ArrayList();

The datatype of an ArrayList is object type, so we can add the elements having the datatype string,
integer and any other.

Add the elements in ArrayList

To add values, the Add() method is used.

The following code describes how we add the elements to the ArratList.
namespace ArrayList1
{
class Program
{
static void Main(string[] args)
{
ArrayList arr = new ArrayList();
();
arr.Add("Sunday");
arr.Add("Monday");
arr.Add("Tuesday");
arr.Add("Wednesday");
arr.Add("Thusday");
arr.Add("Friday");
arr.Add("Saturday");
Console.WriteLine("The
"The elements of the ArrayList are:");
are:"
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
}
}
}
Ref: C#Corner Pick “N” Share :C#Notes

Methods And properties.

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ArrayList arr = new ArrayList();
arr.Add("Sunday");
arr.Add("Monday");
arr.Add("Tuesday");
arr.Add("Wednesday");
Console.WriteLine("*******Properties*********");
Console.WriteLine("Capacity of Elements {0}" , arr.Capacity);
arr.Add("Thusday");
arr.Add("Friday");
arr.Add("Saturday");
Console.WriteLine("Capacity of Elements NOW {0}", arr.Capacity);
Console.WriteLine("Total Number of Elements in List {0}", arr.Count);
Console.WriteLine("The elements of the ArrayList are:");
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
Console.WriteLine("*******Methods*********");
arr.Clear(); //to clear ArrayList
Console.WriteLine("After Clear Number of Elements in List {0}", arr.Count);
arr.Insert(0,"Saqib"); //to insert elements in the ArrayList
arr.Insert(1, "Numan");
arr.Insert(2, "Azeem");
Console.WriteLine(arr);
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
Console.WriteLine("*******After Remove*******");
arr.Remove( "Saqib"); // to remove element
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
}
}
}

9|Page “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

Hashtable
A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage
location and is immutable and cannot have duplicate entries in the Hashtable. The .Net Framework has
provided a Hash Table class that contains all the functionality required to implement a hash table without
any additional development. The hash table is a general-purpose dictionary collection. Each item within the
collection is a DictionaryEntry object with two properties: a key object and a value object. These are
known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This
code is hidden from the developer. All access to the table's values is achieved using the key object for
identification. As the items in the collection are sorted according to the hidden hash code, the items should
be considered to be randomly ordered.

The Hashtable Collection


The Base Class libraries offers a Hashtable Class that is defined in the System.Collectionsnamespace, so you don't
have to code your own hash tables. It processes each key of the hash that you add every time and then uses the hash
code to look up the element very quickly. The capacity of a hash table is the number of elements the hash table can
hold. As elements are added to ahash table, the capacity is automatically increased as required through reallocation.
It is an older .Net Framework type.

Declaring a Hashtable
The Hashtable class is generally found in the namespace called System.Collections. So to execute any of the
examples, we have to add using System.Collections; to the source code.The declaration for the Hashtable is:
Hashtable HT = new Hashtable();
This new Hashtable has the limited capacity and when the limit is reached then the capacity is automatically
increased to allow for further storage. Since the nature of the Hashtable dictionary is that the capacity is always
considered to be approximate we can set the initial approximate capacity by passing the integer parameteger to the
constructor as:
Hashtable HT = new Hashtable(100);
This is useful when the maximum size of the collection is known because it removes the need of resizing the hash
table and also it increases the performance.

Properties of Hashtable
Some of the important properties of a hash table are:

 Comparer: Gets or Sets the IComparer to use for the Hash Table.

 Count: Gets the number of key/value pairs contained in the hash table.

 IsReadOnly: Get a value indicating whether the hash table is read-only.

 Item: Gets or Sets the value associated with the specified Key.

 Keys: Gets an ICollection containing the keys in the hash table.

 Values: Gets an ICollection containing the values in the hash table.

Methods of Hashtable
Some of the important methods of a hash table are:

 Add: Adds an element with the specified key and value in the hash table.

 Clear: Removes all the elements in the hash table.

 ContainsKey: Determined whether the hash table contains a specified key or not.

 ContainsValue: Determined whether the hash table contains a specified value or not.

10 | P a g e “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

Example
static void Main(string[] args)
{
Hashtable HT = new Hashtable
Hashtable();
HT.Add(1, "N");
HT.Add(2, "U");
HT.Add(3, "M");
HT.Add(4, "A");
HT.Add(5, "N");

foreach (object i in HT.Key


HT.Keys)
Console.WriteLine(i);
.WriteLine(i);
foreach (object J in HT.Values)
Console.WriteLine(J);
.WriteLine(J);
foreach (DictionaryEntry di in HT)
Console.WriteLine("keys={0}
"keys={0} values={1}",
values={1}" di.Key, di.Value);
Console.ReadKey();
}

List
The List(of T) class in .NET represents a strongly typed list of objects that can be accessed by
index. List class is a collection and defined in the System.Collections.Generic namespace and
hence
ence provides most of the collections related built
built-in
in methods and properties including add,
remove, search, and sort.

The Remove method is used to delete an item from the List. The Clear method can be used to
clear all items from the list. The Contains method can be used to find an item.

The following code sample shows how to add items to a List. The code also uses Remove,
Clear, and Contains methods to delete and find items.
Ref: C#Corner Pick “N” Share :C#Notes

Example
static void Main(string[] args)
{
List<string> authors = new List<string>();
Console.WriteLine("\nCapacity: {0}", authors.Capacity);
authors.Add("Numan Ashraf");
authors.Add("Saqib Sajjad");
authors.Add("Muhammad Azeem");
authors.Add("Qaiser Farooq");
authors.Add("Muhammad Talha");
Console.WriteLine();
foreach (string author in authors)
{
Console.WriteLine(author);
}
Console.WriteLine("Number of Authors in List: {0}", authors.Count);
Console.WriteLine("\nContains(\"Author\"): {0}",
authors.Contains("Muhammad Azeem"));
Console.WriteLine("\nInsert(2, \"Pakiza\")");
authors.Insert(2, "Pakiza");
Console.WriteLine();
foreach (string author in authors)
{
Console.WriteLine(author);
}
Console.WriteLine("\nauthors[3]: {0}", authors[3]);
Console.WriteLine("\nRemove(\"Numan Ashraf\")");
authors.Remove("Numan Ashraf");
Console.WriteLine();
foreach (string author in authors)
{
Console.WriteLine(author);
}
Console.WriteLine();
authors.Sort();
Console.WriteLine("Sorted List");
foreach (string author in authors)
{
Console.WriteLine(author);
}
authors.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Capacity: {0}", authors.Capacity);
Console.WriteLine("Count: {0}", authors.Count);
authors.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Capacity: {0}", authors.Capacity);
Console.WriteLine("Count: {0}", authors.Count);
Console.ReadKey();
}

12 | P a g e “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

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.

Methods and Properties of the Stack Class


The following table lists some commonly used properties of the Stack class −

Sr.No. Property & Description

1 Count

Gets the number of elements contained in the Stack.

The following table lists some of the commonly used methods of the Stack class −

Sr.No. Method & Description

1 public virtual void Clear();

Removes all elements from the Stack.

2 public virtual bool Contains(object obj);

Determines whether an element is in the Stack.

3 public virtual object Peek();

Returns the object at the top of the Stack without removing it.

4 public virtual object Pop();

Removes and returns the object at the top of the Stack.

5 public virtual void Push(object obj);

Inserts an object at the top of the Stack.

6 public virtual object[] ToArray();

Copies the Stack to a new array.

13 | P a g e “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

Example
The following example demonstrates use of Stack −

using System;
using System.Collections;

namespace CollectionsApplication {

class Program {

static void Main(string[] args) {


Stack st = new Stack();

st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');

Console.WriteLine("Current stack: ");


foreach (char c in st) {
Console.Write(c + " ");
}
Console.WriteLine();

st.Push('V');
st.Push('H');
Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
Console.WriteLine("Current stack: ");
foreach (char c in st) {
Console.Write(c + " ");
}

Console.WriteLine();

Console.WriteLine("Removing values ");


st.Pop();
st.Pop();
st.Pop();

Console.WriteLine("Current stack: ");


foreach (char c in st) {
Console.Write(c + " ");
}
}
}
}

When the above code is compiled and executed, it produces the following result −
Current stack:
W G M A
The next poppable value in stack: H
Current stack:
H V W G M A
Removing values
Current stack:
G M A

14 | P a g e “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

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.

Methods and Properties of the Queue Class


The following table lists some of the commonly used properties of the Queue class

Sr.No. Property & Description

1 Count

Gets the number of elements contained in the Queue.

The following table lists some of the commonly used methods of the Queue class −

Sr.No. Method & Description

1 public virtual void Clear();

Removes all elements from the Queue.

2 public virtual bool Contains(object obj);

Determines whether an element is in the Queue.

3 public virtual object Dequeue();

Removes and returns the object at the beginning of the Queue.

4 public virtual void Enqueue(object obj);

Adds an object to the end of the Queue.

5 public virtual object[] ToArray();

Copies the Queue to a new array.

6 public virtual void TrimToSize();

Sets the capacity to the actual number of elements in the Queue.

15 | P a g e “A room without books is like a body without a soul”


Ref: C#Corner Pick “N” Share :C#Notes

Example
The following example demonstrates use of Stack −

using System;
using System.Collections;

namespace CollectionsApplication {

class Program {

static void Main(string[] args) {


Queue q = new Queue();

q.Enqueue('A');
q.Enqueue('M');
q.Enqueue('G');
q.Enqueue('W');

Console.WriteLine("Current queue: ");


foreach (char c in q) Console.Write(c + " ");

Console.WriteLine();
q.Enqueue('V');
q.Enqueue('H');
Console.WriteLine("Current queue: ");
foreach (char c in q) Console.Write(c + " ");

Console.WriteLine();
Console.WriteLine("Removing some values ");
char ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);

Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result −
Current queue:
A M G W
Current queue:
A M G W V H
Removing values
The removed value: A
The removed value: M

16 | P a g e “A room without books is like a body without a soul”

You might also like