SlideShare a Scribd company logo
1 of 16
Download to read offline
: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
2 | P a g e “A room without books is like a body without a soul”
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};
Ref: C#Corner Pick “N” Share :C#Notes
3 | P a g e “A room without books is like a body without a soul”
 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.
Ref: C#Corner Pick “N” Share :C#Notes
4 | P a g e “A room without books is like a body without a soul”
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.
Ref: C#Corner Pick “N” Share :C#Notes
5 | P a g e “A room without books is like a body without a soul”
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;
Ref: C#Corner Pick “N” Share :C#Notes
6 | P a g e “A room without books is like a body without a soul”
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. };
Ref: C#Corner
Complete Example
1. Console.WriteLine("Single Dimension
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
11. foreach(string str in strArray)
12. Console.WriteLine(str);
13. }
14. Console.WriteLine("-----------------------------
15. Console.WriteLine("Multi-Dimension
16. string[, ] string2DArray = new string[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
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
51. for (int i = 0; i < intJaggedArray3.Length;
52. Console.Write("Element({0}):
53. for (int j = 0; j < intJaggedArray3[i].Length;
54. Console.Write("{0}{1}",
1) ? "" : " ");
55. }
56. Console.WriteLine();
57. }
58. Console.WriteLine("-----------------------------
Pick “N” Share
Dimension Array Sample");
] {
foreach loop
{
-----------------------------");
Dimension Array Sample");
string[2, 2] {
string2DArray) {
-----------------------------");
Sample");
jagged array
intJaggedArray3.Length; i++) {
"Element({0}): ", i);
intJaggedArray3[i].Length; j++) {
intJaggedArray3[i][j], j == (intJaggedArray3[i].Length
--------------------------");
:C#Notes
(intJaggedArray3[i].Length -
Ref: C#Corner
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
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 elements of the ArrayList are:"
foreach (object obj in arr)
{
Console.WriteLine(obj);
}
}
}
}
Pick “N” Share
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.
To create the ArrayList the following code is used:
The datatype of an ArrayList is object type, so we can add the elements having the datatype string,
elements in ArrayList
To add values, the Add() method is used.
The following code describes how we add the elements to the ArratList.
();
"The elements of the ArrayList are:");
:C#Notes
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
The datatype of an ArrayList is object type, so we can add the elements having the datatype string,
The following code describes how we add the elements to the ArratList.
Ref: C#Corner Pick “N” Share :C#Notes
9 | P a g e “A room without books is like a body without a soul”
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);
}
}
}
}
Ref: C#Corner Pick “N” Share :C#Notes
10 | P a g e “A room without books is like a body without a soul”
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.
Ref: C#Corner
Example
static void Main(string[] args)
{
Hashtable HT = new 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
Console.WriteLine(i);
foreach (object J in HT.Values)
Console.WriteLine(J);
foreach (DictionaryEntry
Console.WriteLine("keys={0} values={1}"
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 provides most of the collections related built
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
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.
Pick “N” Share
Hashtable();
HT.Keys)
.WriteLine(i);
HT.Values)
.WriteLine(J);
di in HT)
"keys={0} values={1}", di.Key, di.Value);
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
ence provides most of the collections related built-in methods and properties including add,
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.
:C#Notes
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
in methods and properties including add,
The Remove method is used to delete an item from the List. The Clear method can be used to
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,
Ref: C#Corner Pick “N” Share :C#Notes
12 | P a g e “A room without books is like a body without a soul”
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();
}
Ref: C#Corner Pick “N” Share :C#Notes
13 | P a g e “A room without books is like a body without a soul”
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.
Ref: C#Corner Pick “N” Share :C#Notes
14 | P a g e “A room without books is like a body without a soul”
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
Ref: C#Corner Pick “N” Share :C#Notes
15 | P a g e “A room without books is like a body without a soul”
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.
Ref: C#Corner Pick “N” Share :C#Notes
16 | P a g e “A room without books is like a body without a soul”
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

More Related Content

What's hot (20)

An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
Array data structure
Array data structureArray data structure
Array data structure
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
Chap09
Chap09Chap09
Chap09
 
Arrays
ArraysArrays
Arrays
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Array
ArrayArray
Array
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
 
Java arrays
Java arraysJava arrays
Java arrays
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays in c language
Arrays in c languageArrays in c language
Arrays in c language
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Array
ArrayArray
Array
 
Array in c++
Array in c++Array in c++
Array in c++
 

Similar to Array and Collections in c#

Similar to Array and Collections in c# (20)

Arrays In General
Arrays In GeneralArrays In General
Arrays In General
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Learn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & ArraysLearn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & Arrays
 
Arrays
ArraysArrays
Arrays
 
2 arrays
2   arrays2   arrays
2 arrays
 
Arrays
ArraysArrays
Arrays
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
Programming in c arrays
Programming in c   arraysProgramming in c   arrays
Programming in c arrays
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
Arrays
ArraysArrays
Arrays
 
C# p9
C# p9C# p9
C# p9
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
Array.pptx
Array.pptxArray.pptx
Array.pptx
 

More from Umar Farooq

Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net ArchitectureUmar Farooq
 
Creating Windows-based Applications Part-I
Creating Windows-based Applications Part-ICreating Windows-based Applications Part-I
Creating Windows-based Applications Part-IUmar Farooq
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#Umar Farooq
 
Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#Umar Farooq
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)Umar Farooq
 
Software process model
Software process modelSoftware process model
Software process modelUmar Farooq
 

More from Umar Farooq (10)

Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Linq in C#
Linq in C#Linq in C#
Linq in C#
 
Creating Windows-based Applications Part-I
Creating Windows-based Applications Part-ICreating Windows-based Applications Part-I
Creating Windows-based Applications Part-I
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#
 
Selection Sort
Selection Sort Selection Sort
Selection Sort
 
Week 9 IUB c#
Week 9 IUB c#Week 9 IUB c#
Week 9 IUB c#
 
Matrix
MatrixMatrix
Matrix
 
Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#Polymorphism, Abstarct Class and Interface in C#
Polymorphism, Abstarct Class and Interface in C#
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
 
Software process model
Software process modelSoftware process model
Software process model
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 

Array and Collections in c#

  • 1. :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
  • 2. Ref: C#Corner Pick “N” Share :C#Notes 2 | P a g e “A room without books is like a body without a soul” 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};
  • 3. Ref: C#Corner Pick “N” Share :C#Notes 3 | P a g e “A room without books is like a body without a soul”  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.
  • 4. Ref: C#Corner Pick “N” Share :C#Notes 4 | P a g e “A room without books is like a body without a soul” 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.
  • 5. Ref: C#Corner Pick “N” Share :C#Notes 5 | P a g e “A room without books is like a body without a soul” 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;
  • 6. Ref: C#Corner Pick “N” Share :C#Notes 6 | P a g e “A room without books is like a body without a soul” 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. };
  • 7. Ref: C#Corner Complete Example 1. Console.WriteLine("Single Dimension 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 11. foreach(string str in strArray) 12. Console.WriteLine(str); 13. } 14. Console.WriteLine("----------------------------- 15. Console.WriteLine("Multi-Dimension 16. string[, ] string2DArray = new string[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 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 51. for (int i = 0; i < intJaggedArray3.Length; 52. Console.Write("Element({0}): 53. for (int j = 0; j < intJaggedArray3[i].Length; 54. Console.Write("{0}{1}", 1) ? "" : " "); 55. } 56. Console.WriteLine(); 57. } 58. Console.WriteLine("----------------------------- Pick “N” Share Dimension Array Sample"); ] { foreach loop { -----------------------------"); Dimension Array Sample"); string[2, 2] { string2DArray) { -----------------------------"); Sample"); jagged array intJaggedArray3.Length; i++) { "Element({0}): ", i); intJaggedArray3[i].Length; j++) { intJaggedArray3[i][j], j == (intJaggedArray3[i].Length --------------------------"); :C#Notes (intJaggedArray3[i].Length -
  • 8. Ref: C#Corner 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 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 elements of the ArrayList are:" foreach (object obj in arr) { Console.WriteLine(obj); } } } } Pick “N” Share 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. To create the ArrayList the following code is used: The datatype of an ArrayList is object type, so we can add the elements having the datatype string, elements in ArrayList To add values, the Add() method is used. The following code describes how we add the elements to the ArratList. (); "The elements of the ArrayList are:"); :C#Notes 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 The datatype of an ArrayList is object type, so we can add the elements having the datatype string, The following code describes how we add the elements to the ArratList.
  • 9. Ref: C#Corner Pick “N” Share :C#Notes 9 | P a g e “A room without books is like a body without a soul” 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); } } } }
  • 10. Ref: C#Corner Pick “N” Share :C#Notes 10 | P a g e “A room without books is like a body without a soul” 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.
  • 11. Ref: C#Corner Example static void Main(string[] args) { Hashtable HT = new 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 Console.WriteLine(i); foreach (object J in HT.Values) Console.WriteLine(J); foreach (DictionaryEntry Console.WriteLine("keys={0} values={1}" 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 provides most of the collections related built 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 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. Pick “N” Share Hashtable(); HT.Keys) .WriteLine(i); HT.Values) .WriteLine(J); di in HT) "keys={0} values={1}", di.Key, di.Value); 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 ence provides most of the collections related built-in methods and properties including add, 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. :C#Notes 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 in methods and properties including add, The Remove method is used to delete an item from the List. The Clear method can be used to 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,
  • 12. Ref: C#Corner Pick “N” Share :C#Notes 12 | P a g e “A room without books is like a body without a soul” 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(); }
  • 13. Ref: C#Corner Pick “N” Share :C#Notes 13 | P a g e “A room without books is like a body without a soul” 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.
  • 14. Ref: C#Corner Pick “N” Share :C#Notes 14 | P a g e “A room without books is like a body without a soul” 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
  • 15. Ref: C#Corner Pick “N” Share :C#Notes 15 | P a g e “A room without books is like a body without a soul” 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.
  • 16. Ref: C#Corner Pick “N” Share :C#Notes 16 | P a g e “A room without books is like a body without a soul” 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