System.Collections is a namespace which contains classes and interfaces that manages a group of data. It stores each data in the form of a system.object type. Therefore, a group of value type data always gets boxed/unboxed. It defines multiple data structures to store and retrieve data such as list, queue, and
hashtable.
ArrayList
It’s an array of objects which can grow and shrink its size dynamically. Unlike arrays, an ArrayList can hold data of multiple data types. It can be accessed by its index. Inserting and deleting an element at the middle of an ArrayList is more costly than inserting or deleting an element at the end an ArrayList.
An ArrayList contains many methods and properties that help to manage a group of objects. The following is a list of some frequently used properties and methods defined in an ArrayList.
Table 4-2. Frequently used classes in system.collections namespace
Class
Explanation
ArrayList Array of objects whose size can grow and shrink dynamically Hashtable Collection of key/value pair, organize on base of hash code Queue Manages group of data in First In, First Out (FIFO) order Stack Manages group of data in Last In, First Out (LIFO) order
Code Snippet
Listing 4-13. Use ArrayList to manage a group of objects
using System.Collections; class Program
{
static void Main(string[] args) {
ArrayList arraylist = new ArrayList(); //add objects in arraylist
arraylist.Add(22); arraylist.Add("Ali"); arraylist.Add(true);
//Iterate over each index of arraylist for (int i = 0; i < arraylist.Count; i++) {
System.Console.WriteLine(arraylist[i]); }
arraylist.Remove(22); System.Console.WriteLine(); foreach (var item in arraylist) {
System.Console.WriteLine(item); }
} }
Table 4-3. Frequently used methods and properties of ArrayList
Method and Property
Explanation
Add() Add an object to the end of ArrayList Contains() Return true if specific object is in ArrayList Clone() Create a shallow copy of ArrayList
Remove() Remove the first occurance of specific object in ArrayList RemoveAt() Remove the object from specific index of ArrayList Clear() Remove all objects from the ArrayList
Count Get the actual number of objects stored in ArrayList Capacity Get or Set number of objects that ArrayList can contain
//Output 22 Ali True Ali True
Hashtable
Hashtable stores each element of a collection in a pair of key/values. It optimizes the lookups by computing the hash key and stores it to access the value against it.
Below are some common methods and properties used in a Hashtable class.
Code Snippet
Listing 4-14. Manage company and its owner info in Hashtable
using System.Collections; using System;
class Program {
static void Main(string[] args) {
Hashtable owner = new Hashtable(); //Add some values in Hashtable
//There are no keys but value can be duplicate owner.Add("Bill", "Microsoft");
owner.Add("Paul", "Microsoft"); owner.Add("Steve", "Apple"); owner.Add("Mark", "Facebook");
Table 4-4. Frequently used methods and properties of Hashtable
Method and Property
Explanation
Add() Add an element with the specified key and value ContainsKey() Return true if specific key is in Hashtable ContainsValue Return true if specific value is in Hashtable Clone() Create a shallow copy of Hashtable
Remove() Remove the element with the specified key from ArrayList Clear() Remove all objects from the Hashtable
Count Get the actual number of key/value pairs in Hashtable Keys Get list of keys contains in Hashtable
//Display value against key
Console.WriteLine("Bill is the owner of {0}", owner["Bill"]); //ContainsKey can be use to test key before inserting
if (!owner.ContainsKey("Trump")) {
owner.Add("Trump", "The Trump Organization"); }
// When you use foreach to enumerate hash table elements, // the elements are retrieved as KeyValuePair objects. //DictionaryEntry is the pair of key & value
Console.WriteLine();
foreach (DictionaryEntry item in owner) {
Console.WriteLine("{0} is owner of {1}", item.Key, item.Value); }
//Get All values stored in Hashtable var allValues = owner.Values; Console.WriteLine();
foreach (var item in allValues) { Console.WriteLine("Company: {0}", item); } } } //Output
Bill is the owner of Microsoft Steve is the owner of Apple
Trump is the owner of The Trump Organization Mark is the owner of Facebook
Bill is the owner of Microsoft Paul is the owner of Microsoft Company: Apple
Company: The Trump Organization Company: Facebook
Company: Microsoft Company: Microsoft
Queue
Queue is a class of System.Collections namespace. It stores and retrieves objects in FIFO (First In, First Out) order. In other words, it manages a collection of objects on a first come, first served basis.
Code Snippet
Listing 4-15. Manage weekday’s name in a queue
using System.Collections; using System;
class Program {
static void Main(string[] args) {
Queue days = new Queue(); //Add(Enque) objects in queus days.Enqueue("Mon"); days.Enqueue("Tue"); days.Enqueue("Wed"); days.Enqueue("Thu"); days.Enqueue("Fri"); days.Enqueue("Sat"); days.Enqueue("Sun");
// Displays the properties and values of the Queue.
Console.WriteLine("Total elements in queue are {0}", days.Count); //Remove and return first element of the queue
Console.WriteLine("{0}", days.Dequeue());
//return first element of queue without removing it from queue //return 'Tue'
Console.WriteLine("{0}", days.Peek()); //Iterate over each element of queue Console.WriteLine();
Table 4-5. Frequently used methods and properties of Queue
Method and Property
Explanation
Enqueue() Add an element to the end of the Queue
Dequeue() Remove and return the object at the beginning of the Queue Peek() Return the object at the beginning of the queue without removing it ToArray() Copy the Queue elements to a new array
Contains() Return true if a specified object is in the Queue Clear() Remove all objects from the Queue
Clone() Create a shallow copy of the Queue Count Get the actual number of objects in Queue
foreach (var item in days) { Console.WriteLine(item); } } } //Output
Total elements in queue are 7 Mon Tue Tue Wed Thu Fri Sat Sun
Stack
Stack is a class of System.Collections namespace. It stores and retrieves objects in LIFO (Last In, First Out) order. In other words, elements pushed at the end will pop first, for example, a pile of plates.
Below are some common methods and properties used in Stack class.
Code Snippet
Listing 4-16. Manage browser history in Stack
using System.Collections; using System;
class Program {
Table 4-6. Frequently used methods and properties of Stack
Method and Property
Explanation
Push() Insert the object at the top of the Stack
Pop() Remove and return object at the top of the Stack
Peek() Return the object at the top of the Stack without removing it ToArray() Copy the Stack elements to a new array
Contains() Return true if a specified object is in the Stack Clear() Remove all objects from the Stack
Clone() Create a shallow copy of the Stack Count Get the actual number of objects in Stack
{
Stack history = new Stack(); //Insert browser history in stack history.Push("google.com");
history.Push("facebook.com/imaliasad"); history.Push("twitter.com/imaliasad"); history.Push("youtube.com");
// Displays the properties and values of the Stack.
Console.WriteLine("Total elements in stack are {0}", history.Count); //Remove and return top element of the Stack
Console.WriteLine("{0}", history.Pop());
//return top element of Stack without removing it from Stack //return 'twitter.com/imaliasad'
Console.WriteLine("{0}", history.Peek()); //Iterate over each element of Stack Console.WriteLine();
foreach (var item in history) { Console.WriteLine(item); } } } //Output
Total elements in stack are 4 youtube.com twitter.com/imaliasad twitter.com/imaliasad facebook.com/imaliasad google.com
System.Collections.Generics
System.Collections.Generics is a namespace which contains classes and interfaces to manage a
strongly-typed collection. In a generic collection, data cannot be boxed/unboxed because data always
gets type-safed. It is faster and better than classes and interfaces defined in System.Collections. It also
defines multiple data structures to store and retrieve data such as List<T>, Queue<T>, Stack<T>, and
List<T>
List<T> is a type-safe collection of objects. List can grow and shrink its size dynamically. With generics support, it can store a collection of any type in a type-safe way. Therefore, it is much faster and optimized than ArrayList.
List<T> contains many methods and properties that help to manage a group of data. The following is list of some frequently used properties and methods defined in List<T>.
Code Snippet
Listing 4-17. Manage objects of multiple types in list<T>
using System.Collections.Generic; using System;
class Person {
public string Name { get; set; } public int Age { get; set; } }
class Program
Table 4-7. Frequently used classes in System.Collections.Generic namespace
Class
Explanation
List<T> List of type-safe objects that can dynamically grow & shrink Dictionary<Tkey,Tvalue> Represents collection of type-safe keys and values
Queue<T> Represents First In, First Out collection of type-safe objects Stack<T> Represents Last In, First Out collection of type-safe objects
Table 4-8. Frequently used methods and properties of List<T>
Method and Property
Explanation
Add() Add an object to the end of the List<T> Contains() Return true if specified object is in List<T> Sort() Sort all the objects of List<T> by using comparer Remove() Remove the first occurance of specific object in List<T> RemoveAt() Remove the object from specified index of List<T> Clear() Remove all objects from the List<T>
Find() Search the object by using specified predicate Count Get the actual number of objects stored in List<T>
{
static void Main(string[] args) {
List<Person> people = new List<Person>(); //Add Person in list
people.Add(new Person { Name = "Ali", Age = 22 }); people.Add(new Person { Name = "Sundus", Age = 21 }); people.Add(new Person { Name = "Hogi", Age = 12 }); //Get total number of person in list
Console.WriteLine("Total person are: {0}", people.Count); //Iterate over each person
Console.WriteLine();
foreach (var person in people) {
Console.WriteLine("Name: {0} - Age: {1}", person.Name, person.Age); }
//Instantiate and populate list of int with values List<int> marks = new List<int>
{ 10, 25, 15, 23 };
//Remove '25' from the list marks.Remove(25);
//Get each element by its index Console.WriteLine();
Console.Write("Marks: ");
for (int i = 0; i < marks.Count; i++) { Console.Write(marks[i] + " "); } } } //Output
Total persono are: 3 Name: Ali - Age: 22 Name: Sundus - Age: 21 Name: Hogi - Age: 12 Marks: 10 15 23